Group by with UNION in Mariadb - pivot

I have this query:
select item_code, item_name, First, Second, Third, `Fourth` from (
(SELECT t.item_code, i.item_name, t.actual_qty AS `First`, '' AS `Second`, '' AS `Third`, '' AS `Fourth` FROM tabBin t JOIN `tabItem` i ON i.name = t.item_code WHERE t.warehouse = "Finished Goods")
UNION
(SELECT t.item_code, i.item_name, '' AS `First`, t.actual_qty AS `Second`, '' AS `Third`, '' AS `Fourth` FROM tabBin t JOIN `tabItem` i ON i.name = t.item_code WHERE t.warehouse = "Tank 01 - 1200 KG")
UNION
(SELECT t.item_code, i.item_name, '' AS `First`, '' AS `Second`, t.actual_qty AS `Third`, '' AS `Fourth` FROM tabBin t JOIN `tabItem` i ON i.name = t.item_code WHERE t.warehouse = "Tank 02 - 1200 KG")
UNION
(SELECT t.item_code, i.item_name, '' AS `First`, '' AS `Second`, '' AS `Third`, t.actual_qty AS `Fourth` FROM tabBin t JOIN `tabItem` i ON i.name = t.item_code WHERE t.warehouse = "Tank 03 - 1200 KG")) as temp
GROUP BY temp.item_code, temp.item_name, temp.First, temp.Second, temp.Third, temp.Fourth
And this is the output:
item_code item_name first, second, third, fourth
fg-plu PLUM 30.000000
fg-plu PLUM 40.000000
fg-plu PLUM 10.000000
fg-plu PLUM 1248.00
I want to group by the item_code and item_name or just item_code.

This really appears to be a pivot query in disguise. Just use MAX with CASE expressions to get the output you want:
SELECT
t.item_code,
i.item_name,
MAX(CASE WHEN t.warehouse='Finished Goods' THEN t.actual_qty END) AS first,
MAX(CASE WHEN t.warehouse='Tank 01 - 1200 KG' THEN t.actual_qty END) AS second,
MAX(CASE WHEN t.warehouse='Tank 02 - 1200 KG' THEN t.actual_qty END) AS third,
MAX(CASE WHEN t.warehouse='Tank 03 - 1200 KG' THEN t.actual_qty END) AS fourth
FROM tabBin t
INNER JOIN tabItem i
ON i.name = t.item_code
GROUP BY
t.item_code,
i.item_name

Solved with
enter code Select i.item_name,IFNULL((select b.actual_qty as i2total
from `tabItem` as i2
join `tabBin` as b on b.item_code = i2.item_code AND i2.item_code = i2.item_code
where b.warehouse = "Finished Goods" AND i2.item_code = i.item_code),0) foa, IFNULL((select b.actual_qty as i2total
from `tabItem` as i2
join `tabBin` as b on b.item_code = i2.item_code AND i2.item_code = i2.item_code
where b.warehouse = "Toros" AND i2.item_code = i.item_code),0) toros, (foa + toros) AS total FROM `tabItem` as i WHERE i.item_group = "products" GROUP BY i.item_name, foa, toros ;
Thanks everyone for help.

Related

No output when one side of UNION is empty

I have an Azure Stream Analytics job that combines the results of multiple queries and outputs them to the same sink. To do this, I define my queries within a WITH statement, then combine them using UNION and then write them to my sink. However, unfortunately I only get an output to my sink whenever all of my queries actually have an output, and this is where it goes wrong.
I have some queries that continuously (every 5 minutes) give an output, but I also have some queries that rare give an output (maybe a few times per day). This causes the output to not get any results, until the queries all have something to return. Does anyone know why this is and how I can fix it? Shouldn't UNION also give results when set A has results, but set B doesn't? I'm running this locally in VS Code, with a live connection to Event Hub by the way.
Here is a simplified example of 2 queries (one with frequent output, one with infrequent output) that goes wrong:
WITH
HarmonizedMeasurements AS (
SELECT
CAST(EHHARM.TimeStamp AS datetime) AS "TimeStamp",
CAST(EHHARM.ValueNumber AS float) AS "ValueNumber",
EHHARM.ValueBit AS "ValueBit",
EHHARM.MeasurementName,
EHHARM.PartName,
EHHARM.ElementId,
EHHARM.ElementName,
EHHARM.ObjectName,
EHHARM.TranslationTableId
FROM EventHubHarmonizedMeasurements AS EHHARM TIMESTAMP BY "TimeStamp"
PARTITION BY TranslationTableId
),
ToerenAandrijvingCategoriesMeasurements AS (
SELECT
AANDRCAT.TimeStamp AS "TimeStamp",
AANDRCAT.ValueNumber AS "ValueNumber",
AANDRCAT.ValueBit AS "ValueBit",
AANDRCAT.MeasurementName AS "MeasurementName",
AANDRCAT.PartName AS "PartName",
AANDRCAT.ElementId AS "ElementId",
AANDRCAT.ElementName AS "ElementName",
AANDRCAT.ObjectName AS "ObjectName",
AANDRCAT.TranslationTableId AS "TranslationTableId",
CASE
WHEN (-5000 < AANDRCAT.ValueNumber AND AANDRCAT.ValueNumber <= -1000) THEN 'Dalen'
WHEN (-1000 < AANDRCAT.ValueNumber AND AANDRCAT.ValueNumber <= -200) THEN 'Dalen Retarderen'
WHEN (-200 < AANDRCAT.ValueNumber AND AANDRCAT.ValueNumber <= 0) THEN 'Stilstand'
WHEN (0 < AANDRCAT.ValueNumber AND AANDRCAT.ValueNumber <= 250) THEN 'Nivelleren'
WHEN (250 < AANDRCAT.ValueNumber AND AANDRCAT.ValueNumber <= 400) THEN 'Heffen Retarderen'
WHEN (400 < AANDRCAT.ValueNumber AND AANDRCAT.ValueNumber <= 5000) THEN 'Heffen'
ELSE 'NoCategory'
END AS "Category"
FROM HarmonizedMeasurements AS AANDRCAT
WHERE
AANDRCAT.ObjectName LIKE 'Schutsluis%' AND
AANDRCAT.MeasurementName = 'Motortoerental terugkoppeling' AND
AANDRCAT.ValueNumber <> 0
),
AandrijvingCatStartMeasurements AS (
SELECT
AANDRCAT.TimeStamp AS "StartTime",
AANDRCAT.Category AS "Category",
AANDRCAT.ElementId AS "ElementId",
AANDRCAT.TranslationTableId AS "TranslationTableId"
FROM ToerenAandrijvingCategoriesMeasurements AS AANDRCAT
WHERE
LAG(Category, 1) OVER (PARTITION BY ElementId LIMIT DURATION(day, 1)) <> Category
),
AandrijvingCatEndMeasurements AS (
SELECT
AANDRST.StartTime AS "EndTime",
LAG(AANDRST.StartTime, 1) OVER (PARTITION BY ElementId LIMIT DURATION(day, 1)) AS "StartTime",
LAG(AANDRST.Category, 1) OVER (PARTITION BY ElementId LIMIT DURATION(day, 1)) AS "Category",
AANDRST.ElementId AS "ElementId",
AANDRST.TranslationTableId AS "TranslationTableId"
FROM AandrijvingCatStartMeasurements AS AANDRST
),
VermogenAandrijvingMeasurements AS (
SELECT
AANDRVER.TimeStamp AS "TimeStamp",
AANDRVER.ValueNumber AS "ValueNumber",
AANDRVER.ValueBit AS "ValueBit",
CONCAT(AANDRVER.MeasurementName, ' ', AANDREN.Category) AS "MeasurementName",
AANDRVER.PartName AS "PartName",
AANDRVER.ElementId AS "ElementId",
AANDRVER.ElementName AS "ElementName",
AANDRVER.ObjectName AS "ObjectName",
AANDRVER.TranslationTableId AS "TranslationTableId"
FROM HarmonizedMeasurements AS AANDRVER
LEFT JOIN AandrijvingCatEndMeasurements AS AANDREN
ON DATEDIFF(minute, AANDRVER, AANDREN) BETWEEN 0 AND 30 AND
AANDRVER.TimeStamp >= AANDREN.StartTime AND
AANDRVER.Timestamp < AANDREN.EndTime AND
AANDRVER.ElementId = AANDREN.ElementId AND
AANDRVER.TranslationTableId = AANDREN.TranslationTableId
INNER JOIN SQLMeasurementType AS MEAS
ON MEAS.Name = CONCAT(AANDRVER.MeasurementName, ' ', AANDREN.Category)
WHERE
AANDRVER.ObjectName LIKE 'Schutsluis%' AND
AANDRVER.MeasurementName = 'Vermogen'
),
LockDoorTop AS (
SELECT
Lock.TimeStamp AS "TimeStamp",
Lock.ValueNumber AS "ValueNumber",
Lock.ValueBit AS "ValueBit",
Lock.MeasurementName,
Lock.PartName,
Lock.ElementId,
Lock.ElementName,
Lock.ObjectName,
Lock.TranslationTableId
FROM HarmonizedMeasurements AS Lock
WHERE
Lock.MeasurementName = 'Sluisdeur open' AND
Lock.ElementName = 'Deur sluiskolk 1' AND
Lock.PartName = 'Bovenhoofd' AND
Lock.ValueBit = '1'
),
WaterLTop AS (
SELECT
WaterTop.TimeStamp AS "TimeStamp",
WaterTop.ValueNumber AS "ValueNumber",
WaterTop.ValueBit AS "ValueBit",
WaterTop.MeasurementName,
WaterTop.PartName,
WaterTop.ElementId,
WaterTop.ElementName,
WaterTop.ObjectName,
WaterTop.TranslationTableId
FROM HarmonizedMeasurements AS WaterTop
WHERE
WaterTop.MeasurementName = 'Waterniveaumeting' AND
WaterTop.ElementName = 'Sluiskolk 1' AND
WaterTop.PartName = 'Opvaartzijde'
),
WaterLLock AS (
SELECT
WaterLock.TimeStamp AS "TimeStamp",
WaterLock.ValueNumber AS "ValueNumber",
WaterLock.ValueBit AS "ValueBit",
WaterLock.MeasurementName,
WaterLock.PartName,
WaterLock.ElementId,
WaterLock.ElementName,
WaterLock.ObjectName,
WaterLock.TranslationTableId
FROM HarmonizedMeasurements AS WaterLock
WHERE
WaterLock.MeasurementName = 'Waterniveaumeting' AND
WaterLock.ElementName = 'Sluiskolk 1' AND
WaterLock.PartName = 'Sluiskamer'
),
WaterLevelTopMeasurements AS (
SELECT
LockDoor.TimeStamp AS "TimeStamp",
CAST(ROUND((WaterLevelLock.ValueNumber - WaterLevelTop.ValueNumber), 2) AS float) AS "ValueNumber",
null AS "ValueBit",
MEAS.Name AS "MeasurementName",
LockDoor.PartName AS "PartName",
LockDoor.ElementId AS "ElementId",
LockDoor.ElementName AS "ElementName",
LockDoor.ObjectName AS "ObjectName",
LockDoor.TranslationTableId AS "TranslationTableId"
FROM LockDoorTop AS LockDoor
JOIN WaterLTop AS WaterLevelTop
ON DATEDIFF(minute, LockDoor, WaterLevelTop) BETWEEN 0 AND 1 AND
LockDoor.ObjectName = WaterLevelTop.ObjectName
JOIN WaterLLock AS WaterLevelLock
ON DATEDIFF(minute, LockDoor, WaterLevelLock) BETWEEN 0 AND 1 AND
LockDoor.ObjectName = WaterLevelLock.ObjectName
INNER JOIN SQLMeasurementType AS MEAS
ON MEAS.Name = 'Waterniveauverschil'
),
-- Combine queries
DatalakeCombinedMeasurements AS (
SELECT * FROM VermogenAandrijvingMeasurements
UNION
SELECT * FROM WaterLevelTopMeasurements
)
-- Output data
SELECT *
INTO DatalakeHarmonizedMeasurements
FROM DatalakeCombinedMeasurements
PARTITION BY TranslationTableId

How can I prevent sql injection with groovy?

I have a sql like:
String sql = """SELECT id, name, sex, age, bron_year, address, phone, state, comment, is_hbp, is_dm, is_cva, is_copd, is_chd, is_cancer, is_floating, is_poor, is_disability, is_mental
FROM statistics_stin WHERE 1=1
${p.team_num == 0 ? "" : "AND team_num = ${p.team_num}"}
${p.zone == 0 ? "" : "AND team_id = ${p.zone}"}
${p.is_hbp == 2 ? "" : "AND is_hbp = ${p.is_hbp}"}
${p.is_dm == 2 ? "" : "AND is_dm = ${p.is_dm}"}
${p.is_chd == 2 ? "" : "AND is_chd = ${p.is_chd}"}
${p.is_cva == 2 ? "" : "AND is_cva = ${p.is_cva}"}
${p.is_copd == 2 ? "" : "AND is_copd = ${p.is_copd}"}
${p.is_cancer == 2 ? "" : "AND is_cancer = ${p.is_cancer}"}
${p.is_floating == 2 ? "" : "AND is_floating = ${p.is_floating}"}
${p.is_poor == 2 ? "" : "AND is_poor = ${p.is_poor}"}
${p.is_disability == 2 ? "" : "AND is_disability = ${p.is_disability}"}
${p.is_mental == 2 ? "" : "AND is_mental = ${p.is_mental}"}
${p.is_aged == 2 ? "" : (p.is_aged == 1 ? " AND age >= 65" : " AND age < 65")}
${p.is_prep_aged == 2 ? "" : (p.is_prep_aged == 1 ? "AND (age BETWEEN 60 AND 64)" : "AND (age < 60 OR age > 64)")}
${p.is_young == 2 ? "" : (p.is_young == 1 ? " AND age < 60" : " AND age >= 60")}
ORDER BY team_id ASC, id ASC
LIMIT ${start}, ${page_size}
""";
Then use :
def datasource = ctx.lookup("jdbc/mysql");
def executer = Sql.newInstance(datasource);
def rows = executer.rows(sql);
Here the p is a json object like:
p = {is_aged=2, is_cancer=2, is_chd=1, is_copd=2, is_cva=2, is_disability=2, is_dm=2, is_floating=2, is_hbp=1, is_mental=2, is_poor=2, pn=1, team_num=0, zone=0}
This way has sql injection. I know I can use params type like:
executer.rows('SELECT * from statistics_stin WHERE is_chd=:is_chd', [is_chd: 1]);
But this case has to many AND conditions, use or not will be decided by the json p.
How to do this please?
You have a problem of dynamic SQL binding, i.e. the number of bind parameters is not constant, but depend on the input.
There is an elegant solution from Tom Kyte
which has even more elegant implementation in Groovy
The basic idea is simple bind all variables, the variables that have an input value and should be used are processed normally, e.g
col1 = :col1
the variables that have no input (and shall be ignored) are binded with a dummy construct:
(1=1 or :col2 is NULL)
i.e. they are effectively ignored by shortcut evaluation.
Here two examples for three columns
def p = ["col1" : 1, "col2" : 2, "col3" : 3]
This input leads to a full query
SELECT col1, col2, col3
FROM tab WHERE
col1 = :col1 AND
col2 = :col2 AND
col3 = :col3
ORDER by col1,col2,col3
For limited input
p = [ "col3" : 3]
you get this query
SELECT col1, col2, col3
FROM tab WHERE
(1=1 or :col1 is NULL) AND
(1=1 or :col2 is NULL) AND
col3 = :col3
ORDER by col1,col2,col3
Here the Groovy creation of the SQL Statement
String sql = """SELECT col1, col2, col3
FROM tab WHERE
${(!p.col1) ? "(1=1 or :col1 is NULL)" : "col1 = :col1"} AND
${(!p.col2) ? "(1=1 or :col2 is NULL)" : "col2 = :col2"} AND
${(!p.col3) ? "(1=1 or :col3 is NULL)" : "col3 = :col3"}
ORDER by col1,col2,col3
"""
You can even get rid of the ugly 1=1 predicate;)
Another option is to build your bindings as you build the query then execute the appropriate implementation of rows
def query = new StringBuilder( "SELECT id, name, sex, age, bron_year, address, phone, state, comment, is_hbp, is_dm, is_cva, is_copd, is_chd, is_cancer, is_floating, is_poor, is_disability, is_mental FROM statistics_stin WHERE 1=1" )
def binds = []
if ( p.team_num == 0 ) {
query.append( ' AND team_num = ? ' )
binds << p.team_num
}
if ( p.zone == 0 ) {
query.append( ' AND team_id = ? ' )
binds << p.zone == 0
}
...
executer.rows(query.toString(), binds);

Could not add table 'SELECT('

Error given when adding query that runs in SQL developer but not in MS Query. Seems to not like my nested query.
Code I am using:
SELECT ORDER_DATE
,SALES_ORDER_NO
,CUSTOMER_PO_NUMBER
,DELIVER_TO
,STATUS
,ITEM_NUMBER
,DESCRIPTION
,ORD_QTY
,SUM(QUANTITY) AS ON_HAND
,PACKAGE_ID
,PACKAGE_STATUS
,MAX(TRAN_DATE) AS LAST_TRANSACTION
,MIN(DAYS) AS DAYS
FROM (
SELECT TRUNC(SH.ORDER_DATE) AS ORDER_DATE
,SH.SALES_ORDER_NO
,SH.CUSTOMER_PO_NUMBER
,SH.SHIP_CODE AS DELIVER_TO
,SH.STATUS
,SB.ITEM_NUMBER
,IM.DESCRIPTION
,SB.ORD_QTY
,BID.QUANTITY
,SPM.PACKAGE_ID
,CASE
WHEN SPM.SHIPPED = 'Y'
THEN 'SHIPPED'
WHEN SPM.STATUS = 'C'
THEN 'PACKED'
WHEN BID.QUANTITY IS NOT NULL
THEN 'AVAILABLE'
WHEN BID.QUANTITY IS NULL
THEN 'UNAVAILABLE'
END AS PACKAGE_STATUS
,CASE
WHEN SPM.SHIPPED = 'Y'
THEN TRUNC(SPM.BILLING_DATE)
WHEN SPM.STATUS = 'C'
THEN TRUNC(SPM.END_TIME)
WHEN BID.QUANTITY IS NOT NULL
THEN TRUNC(BID.ACTIVATION_TIME)
END AS TRAN_DATE
,CASE
WHEN SPM.SHIPPED = 'Y'
THEN ROUND(SYSDATE - SPM.BILLING_DATE, 0)
WHEN SPM.STATUS = 'C'
THEN ROUND(SYSDATE - SPM.END_TIME, 0)
WHEN BID.QUANTITY IS NOT NULL
THEN ROUND(SYSDATE - BID.ACTIVATION_TIME, 0)
END AS DAYS
FROM SO_HEADER SH
LEFT JOIN SO_BODY SB ON SB.SO_HEADER_TAG = SH.SO_HEADER_TAG
LEFT JOIN SO_PACKAGE_MASTER SPM ON SPM.PACKAGE_ID = SB.PACKAGE_ID
LEFT JOIN ITEM_MASTER IM ON IM.ITEM_NUMBER = SB.ITEM_NUMBER
LEFT JOIN V_BIN_ITEM_DETAIL BID ON BID.ITEM_NUMBER = SB.ITEM_NUMBER
WHERE SH.ORDER_TYPE = 'MSR'
AND (
SB.REASON_CODE IS NULL
OR SB.REASON_CODE NOT LIKE 'CANCEL%'
)
AND (
IM.DESCRIPTION NOT LIKE '%CKV%'
OR IM.DESCRIPTION IS NULL
AND IM.ITEM_NUMBER IS NOT NULL
)
)
WHERE PACKAGE_STATUS <> 'SHIPPED'
GROUP BY ORDER_DATE
,SALES_ORDER_NO
,CUSTOMER_PO_NUMBER
,DELIVER_TO
,STATUS
,ITEM_NUMBER
,DESCRIPTION
,ORD_QTY
,PACKAGE_ID
,PACKAGE_STATUS
ORDER BY (
CASE PACKAGE_STATUS
WHEN 'AVAILABLE'
THEN 1
WHEN 'UNAVAILABLE'
THEN 2
WHEN 'PACKED'
THEN 3
END
)
,LAST_TRANSACTION;
Is there any option I can select that will allow me to run this query?

Dynamic Pivot without Null value

This is a dynamic crosstab query in Northwind database:
DECLARE #COUNTRY NVARCHAR(MAX) ='', #COUNTRY2 NVARCHAR(MAX)
SELECT #COUNTRY = #COUNTRY + QUOTENAME(Country)+', '
FROM Customers
GROUP BY Country
SET #COUNTRY= LEFT(#COUNTRY, LEN(#COUNTRY)-1)
SET #COUNTRY2 = REPLACE(#COUNTRY, ',' , '+')
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = 'SELECT * , '+#COUNTRY2+' AS TOTAL
FROM (SELECT E.EmployeeID, E.LastName,
ISNULL( OD.Quantity, 0)* ISNULL(OD.[UnitPrice],0) QU,
O.ShipCountry AS CO
FROM Orders O JOIN Employees E ON O.EmployeeID = E.EmployeeID
JOIN [dbo].[Order Details] OD ON OD.OrderID = O.OrderID) AS T
PIVOT(SUM(QU) FOR CO IN ('+#COUNTRY+')) AS PVT
ORDER BY 1'
EXEC(#SQL)
I need to change the code in a way that have Null values replaced by 0.
DECLARE #COUNTRY NVARCHAR(MAX) = '' ,
#COUNTRY2 NVARCHAR(MAX);
SELECT #COUNTRY = #COUNTRY + COALESCE(QUOTENAME(Country) + ', ', '')
FROM Customers
WHERE EXISTS ( SELECT *
FROM [Orders] AS [o]
WHERE o.[CustomerID] = Customers.[CustomerID] )
GROUP BY Country;
SET #COUNTRY = LEFT(#COUNTRY, LEN(#COUNTRY) - 1);
SET #COUNTRY2 = REPLACE(#COUNTRY, ',', '+');
DECLARE #SQL NVARCHAR(MAX);
SET #SQL = 'SELECT * , ' + #COUNTRY2 +
' AS TOTAL
FROM (
SELECT oe.EmployeeID, oe.LastName, oe.ShipCountry AS CO,
COALESCE(OD.Quantity * OD.UnitPrice, 0) AS QU
FROM (
SELECT EmployeeID, LastName, ShipCountry
FROM (
SELECT DISTINCT
ShipCountry
FROM Orders
) o ,
Employees
) oe
LEFT JOIN Orders O ON O.EmployeeID = oe.EmployeeID AND
[oe].[ShipCountry] = [O].[ShipCountry]
LEFT JOIN [Order Details] OD ON OD.OrderID = O.OrderID
) AS T
PIVOT(SUM(QU) FOR CO IN (' + #COUNTRY + ')) AS PVT
ORDER BY 1';
EXEC(#SQL);
You need to change the SELECT * to:
SELECT ISNULL(Argentina,0) AS 'Argentina' , INSNULL(Belgium,0) AS 'Belgium' , ....
Ofcourse, you would need to change your dynamic query to reflect the ISNULL functions.
Good Luck

Exporting stored procedure result to excel

Similar Question may have been asked on this forum regarding exporting stored procedure result to excel file,I've tried few attempts to this but the file does not export to the folder that I expect,Your help is appreciated
Stored Procedure that I created
/****** Object: StoredProcedure [dbo].[Copy_DataDump_SpecificQuery] Script Date: 10/28/2014 15:59:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[Copy_DataDump_SpecificQuery]
#SQLScript VARCHAR(MAX)
,#OutPut_Number INT OUTPUT
,#Output_FIleName VARCHAR(MAX) OUTPUT
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
BEGIN TRY
DECLARE #server Varchar (100)
SET #server = 'MyServerName'
DECLARE #FileName VARCHAR(255)
DECLARE #Date VARCHAR(12)
SELECT #Date = CONVERT(VARCHAR(10),GETDATE(),120)
SET #Output_FIleName = CAST(NEWID() AS VARCHAR(MAX))+ '.xls'
DECLARE #FilePath VARCHAR (4000)
SET #FilePath = '\\ComputerName\Users\MyUserName\Downloads\Exel_File' + #Output_FIleName ;
IF OBJECT_ID('tempDB..##temp_Query', 'U') IS NOT NULL
DROP TABLE ##temp_Query;
----------------------------------------------------------------------------------------------
DECLARE #Query AS VARCHAR(MAX)
DECLARE #FROM_Start INT
SELECT #FROM_Start = CHARINDEX(' FROM ',#SQLScript)
SELECT #Query = SUBSTRING(#SQLScript,0,#FROM_Start) + ' INTO ##temp_Query FROM ' + SUBSTRING(#SQLScript,#FROM_Start+6,LEN(#SQLScript))
PRINT (#Query)
Exec(#Query)
------------------------------------------------------------------------------------------------------------------
DECLARE #dbName VARCHAR (100)
SET #dbName = 'master'
DECLARE #sql VARCHAR (5000)
SET #sql = 'Select * from tempdb.dbo.##temp_Query'
DECLARE #dbName1 VARCHAR (100)
IF OBJECT_ID ('tempDB..##TempExport_Query1','U') is not null
DROP TABLE ##TempExport_Query1
IF OBJECT_ID ('tempDB..##TempExport_Query2','U') is not null
DROP TABLE ##TempExport_Query2
SELECT #dbName1 = #dbName
SELECT #dbName = 'use ' + #dbName + ';'
DECLARE #columnNames VARCHAR (8000), #columnConvert VARCHAR (8000), #tempSQL VARCHAR (8000)
SELECT
#tempSQL = LEFT(#sql, CHARINDEX('from', #sql) - 1) + ' into ##TempExport_Query1 ' +
SUBSTRING(#sql, CHARINDEX('from', #sql) - 1, LEN(#sql))
EXEC (#dbName + #tempSQL)
--SELECT *
--FROM tempdb.INFORMATION_SCHEMA.Columns
--WHERE table_name = '##TempExport_Query1'
SELECT #columnNames = COALESCE(#columnNames + ',', '') + '"' + column_name + '"',
#columnConvert = COALESCE(#columnConvert + ',', '') + 'convert(nvarchar(4000),'
+ '[' + column_name + ']' + CASE
WHEN data_type IN ('datetime', 'smalldatetime') THEN ',121'
WHEN data_type IN ('numeric', 'decimal') THEN ',128'
WHEN data_type IN ('float', 'real', 'money', 'smallmoney') THEN ',2'
WHEN data_type IN ('datetime', 'smalldatetime') THEN ',120' ELSE ''
END + ') as ' + '[' + column_name + ']'
FROM tempdb.INFORMATION_SCHEMA.Columns
WHERE table_name = '##TempExport_Query1'
-- execute select query to insert data and column names into new temp table
SELECT #sql = 'select ' + #columnNames + 'temp##SortID into ##TempExport_Query2 from (select ' + #columnConvert + ',
''2'' as temp##SortID
from ##TempExport_Query1 union all select ''' + REPLACE(#columnNames, ',', ''', ''') + ''',
''1'') t '
EXEC (#sql)
SET #sql = 'bcp " select * from ##TempExport_Query2 ORDER BY temp##SortID " queryout "' + #FilePath +
'" -U uno -P uno -c -T -S ' + #server
EXEC master..xp_cmdshell #sql
SET #OutPut_Number = 1
END TRY
BEGIN CATCH
--DECLARE #ErrorDescription VARCHAR(1000) = 'ERROR - ' + ERROR_MESSAGE()
-- RAISERROR(#ErrorDescription,16,1)
SET #OutPut_Number = 2
--SET #OutPut_Message = ##ERROR
END CATCH
End
Parameters
DECLARE #OutPut_Number INT;
DECLARE #OutPut_Message VARCHAR(1000);
EXECUTE dbo.Copy_DataDump_SpecificQuery 'SELECT O.ID AS SystemNumber
,'' AS ManualNumber
,O.Date AS InvoiceDate
,OT.ID AS CustomerCode
,OT.Name AS CustomerName
,I.ID AS ItemID
,I.Description AS Item
,OL.UnitQty
,OL.FreeQty
,OL.UnitPrice
,OL.GrossValue
,NetSaleValue
,DueDate = ''
,A.ID AS SalesRepCode
,ItemCostPrice = OL.UnitPrice
FROM TxnOrder O
INNER JOIN TxnOrderLine OL ON O.UID = OL.TxnOrderUID AND O.SiteUID = Ol.TxnOrder_SiteUID
INNER JOIN Outlet OT ON O.OutletUID = OT.UID
INNER JOIN Item I ON OL.ItemUID = I.UID
INNER JOIN Agent A ON O.AgentUID = A.UID
WHERE O.mpt_TypeEnum = 1
AND( O.IsPrinted = 1 OR O.mpt_SalesmodelEnum = 2)
--AND O.Date >= #StartDate AND O.Date <= #EndDate
--AND (#DistributorUID IS NULL OR O.DistributorUID = #DistributorUID)
--AND (#AgentUID IS NULL OR O.AgentUID = #AgentUID)'
,#OutPut_Number OUTPUT
,#OutPut_Message OUTPUT
SELECT #OutPut_Message
After I execute I receive the following Output on the SQL Output window
69111E97-BEDE-4BDE-9EBE-C063DB690E9F.xls
I have created the permission for the folder as per below screenshot
This Problem was resolved ,I Logged in to the server via RDP and I executed the SP as per below and it worked out..
DECLARE #OutPut_Number INT;
DECLARE #OutPut_Message VARCHAR(1000);
EXECUTE dbo.Copy_DataDump_SpecificQuery 'SELECT O.ID AS SystemNumber
,O.Date AS InvoiceDate
,OT.ID AS CustomerCode
,OT.Name AS CustomerName
,I.ID AS ItemID
,I.Description AS Item
,OL.UnitQty
,OL.FreeQty
,OL.UnitPrice
,OL.GrossValue
,NetSaleValue
,A.ID AS SalesRepCode
,ItemCostPrice = OL.UnitPrice
FROM TxnOrder O
INNER JOIN TxnOrderLine OL ON O.UID = OL.TxnOrderUID AND O.SiteUID = Ol.TxnOrder_SiteUID
INNER JOIN Outlet OT ON O.OutletUID = OT.UID
INNER JOIN Item I ON OL.ItemUID = I.UID
INNER JOIN Agent A ON O.AgentUID = A.UID
WHERE O.mpt_TypeEnum = 1
AND( O.IsPrinted = 1 OR O.mpt_SalesmodelEnum = 2)'
,#OutPut_Number OUTPUT
,#OutPut_Message OUTPUT
SELECT #OutPut_Message
AND In My select Query I removed the Following Columns
'' AS ManualNumber
DueDate = ''
AND as Im already have the permission to access the server via RDP,I replaced the following path as follows
SET #FilePath = '\\ComputerName\Users\MyUserName\Downloads\Exel_File' + #Output_FIleName
C:\Users\Pathuma\Downloads\Excel
SET #FilePath = '\C:\Users\MyUsername\Downloads\Excel' + #Output_FIleName

Resources