merging the results of a SQL query - sql-server

i am trying to merge the results of this query all data in one list. 'Union' didnt help...
any ideas ?
DECLARE #cnt INT = 0
DECLARE #SQLQuery AS NVARCHAR(500)
DECLARE #items AS VARCHAR(500)
DECLARE #stline AS VARCHAR(500)
while #cnt < 101
begin
set #items = 'LG_0' + convert(nvarchar(3),#cnt) + '_ITEMS'
set #stline = 'LG_0' + convert(nvarchar(3),#cnt) + '_01_STLINE'
if (OBJECT_ID (#items) is not null and OBJECT_ID(#stline) is not null )
set #SQLQuery = 'SELECT
ITM1.CODE, itm1.NAME, max (stl.date_) [latest date] , price as [latest price], '+ convert(nvarchar(3),#cnt) + ' as [proje kodu]
FROM ' + #items + ' ITM1 INNER JOIN ' + #stline + ' STL
ON ITM1.LOGICALREF = STL.STOCKREF
WHERE PRICE > 0
AND TRCODE = 1
AND CANCELLED = 0
AND INVOICEREF > 0
group by code, name, stl.DATE_ , price
'
exec (#SQLQuery)
set #cnt = #cnt +1
end
the result is this :
but i want them all union-ed... (sorry for the mostly code issue, i have to add here more typing)

I don't know why UNION didn't work for you, but the following should work:
DECLARE #cnt INT = 0
DECLARE #SQLQuery AS NVARCHAR(MAX) = ''
DECLARE #items AS VARCHAR(500)
DECLARE #stline AS VARCHAR(500)
while #cnt < 101
begin
set #items = 'LG_0' + convert(nvarchar(3),#cnt) + '_ITEMS'
set #stline = 'LG_0' + convert(nvarchar(3),#cnt) + '_01_STLINE'
if (OBJECT_ID (#items) is not null and OBJECT_ID(#stline) is not null )
set #SQLQuery = #SQLQuery + 'SELECT
ITM1.CODE, itm1.NAME, max (stl.date_) [latest date] , price as [latest price], '+ convert(nvarchar(3),#cnt) + ' as [proje kodu]
FROM ' + #items + ' ITM1 INNER JOIN ' + #stline + ' STL
ON ITM1.LOGICALREF = STL.STOCKREF
WHERE PRICE > 0
AND TRCODE = 1
AND CANCELLED = 0
AND INVOICEREF > 0
GROUP BY code, name, stl.DATE_ , price
UNION ALL
'
set #cnt = #cnt +1
end
-- SUBSTRING to remove last UNION ALL
SELECT #SQLQuery = SUBSTRING(#SQLQuery, 1, LEN(#SQLQuery) - 18)
-- For debugging purposes
-- PRINT #SQLQuery
exec (#SQLQuery)
I couldn't test it, but you can comment the exec, and uncomment the PRINT to see what query is being generated. It makes debugging dynamic SQL a whole lot easier.
The idea behind this code: first the UNION ALL query is being build, based on your conditions. Finally the last UNION ALL is removed, then the code can be executed.

DECLARE #cnt INT = 0
DECLARE #SQLQuery AS NVARCHAR(max)
DECLARE #items AS VARCHAR(500)
DECLARE #stline AS VARCHAR(500)
set #SQLQuery =''
while #cnt < 101
begin
set #items = 'LG_0' + convert(nvarchar(3),#cnt) + '_ITEMS'
set #stline = 'LG_0' + convert(nvarchar(3),#cnt) + '_01_STLINE'
if (OBJECT_ID (#items) is not null and OBJECT_ID(#stline) is not null )
set #SQLQuery = #SQLQuery + 'SELECT
ITM1.CODE, itm1.NAME, max (stl.date_) [latest date] , price as [latest price], '+ convert(nvarchar(3),#cnt) + ' as [proje kodu]
FROM ' + #items + ' ITM1 INNER JOIN ' + #stline + ' STL
ON ITM1.LOGICALREF = STL.STOCKREF
WHERE PRICE > 0
AND TRCODE = 1
AND CANCELLED = 0
AND INVOICEREF > 0
GROUP BY code, name, stl.DATE_ , price
UNION ALL
'
set #cnt = #cnt +1
end
-- SUBSTRING to remove last UNION ALL
--PRINT len(#SQLQuery)
set #SQLQuery = left ( #SQLQuery , len(#SQLQuery)-18)
--PRINT len(#SQLQuery)
-- print #SQLQuery
-- For debugging purposes
-- PRINT #SQLQuery
exec (#SQLQuery)

Related

Dynamic query variable error

I have a table #months as below
MONTH_ID FISCAL_YEAR_MONTH MIN_DATE MAX_DATE
1 FSA201510 20151001 20151031
2 FSA201511 20151101 20151130
3 FSA201512 20151201 20151204
I am using below dynamic query to update a column SCCount in table mastercount(has 3 rows)-
DECLARE #sql VARCHAR(8000), #fym varchar(6)
DECLARE #I INT, #ROWS INT
SET #ROWS=(SELECT count(*) from #MONTHS)
SET #I=1
WHILE #I<=#ROWS
BEGIN
SET #fym=(SELECT RIGHT(FISCAL_YEAR_MONTH,6) from #MONTHS where month_id=#I)
SET #sql = 'UPDATE mastercount'
SET #sql += ' SET SCCount = (SELECT count(*) from '
SET #sql += ' dw_extract.dbo.dw_fsa_' + cast(#fym as varchar(6))+ ') WHERE row=#I'
EXEC (#sql)
SET #I=#I+1
END
This gives an error Must declare the scalar variable "#I".
Why is this happening?
You need to change this
SET #sql += ' dw_extract.dbo.dw_fsa_' + cast(#fym as varchar(6))+ ') WHERE row=#I'
to this
SET #sql += ' dw_extract.dbo.dw_fsa_' + cast(#fym as varchar(6))+ ') WHERE row=' + CAST(#I AS NVARCHAR(10))
That's because #I is not recognized by your dynamic query. You should parameterized #I instead and use sp_executesql to run your query:
DECLARE #sql NVARCHAR(8000), #fym VARCHAR(6)
DECLARE #I INT, #ROWS INT
SET #ROWS = (SELECT COUNT(*) FROM #MONTHS)
SET #I = 1
WHILE #I <= #ROWS
BEGIN
SET #fym = (SELECT RIGHT(FISCAL_YEAR_MONTH,6) FROM #MONTHS WHERE month_id = #I)
SET #sql = N'UPDATE mastercount'
SET #sql += N' SET SCCount = (SELECT count(*) from '
SET #sql += N' dw_extract.dbo.dw_fsa_' + cast(#fym as varchar(6))+ N') WHERE row=#I'
EXEC sp_executesql #sql, N'#I INT', #I
SET #I = #I + 1
END

mssql dynamic query entity does not get values

hello this my dynamic query and this procedure I did tested is working.
but Does not bring data to the server-side (entity)
visual studio 2012
framework 4.5
entity store procedure
public IEnumerable<spGetInvoiceDetailSearch_Result> GetInvoiceDetailedSearch(InvoiceModel item)
{
return DALContext.GetInvoiceDetailedSearch(item);
}
ALTER PROCEDURE [dbo].[spGetInvoiceDetailSearch] #InvoiceItemID INT
,#InvoiceTypeID INT
,#VesselID INT
,#PaidBy NVARCHAR(50)
,#InvoiceNo NVARCHAR(50)
,#CompanyID INT
,#InvoiceFromDate DATE
,#InvoiceToDate DATE
,#FromDueDate DATE
,#ToDueDate DATE
,#FromAmount DECIMAL(18, 4)
,#ToAmount DECIMAL(18, 4)
,#DueDateType NVARCHAR(50)
AS
BEGIN
DECLARE #SQLQuery AS NVARCHAR(4000)
SELECT #SQLQuery =
'SELECT dbo.Invoices.InvoiceID, dbo.Invoices.CompanyID, dbo.Invoices.VesselID, dbo.Invoices.InvoiceNo, dbo.Invoices.DueDate, dbo.Invoices.Amount,
dbo.Invoices.Comment, dbo.Invoices.IsPaid, dbo.Invoices.PaymentDate, dbo.Invoices.PaidBy, dbo.Invoices.Period, dbo.Invoices.InvoiceDate,
dbo.Invoices.InvoiceCurrencyCode, dbo.Invoices.InvoiceAmount, dbo.Invoices.IsReceived, dbo.Invoices.IsProforma, dbo.Invoices.InvoiceTypeID,
dbo.Invoices.IsDeleted, dbo.Invoices.Parity, dbo.Invoices.DueDateType, dbo.Vessels.Name AS VesselName, dbo.InvoiceVsInvoiceItems.ItemPrice as ItemPrice,
dbo.InvoiceVsInvoiceItems.InvoiceItemID as InvoiceItemID, dbo.InvoiceVsInvoiceItems.VAT as VAT, dbo.InvoiceVsInvoiceItems.ItemType as ItemType, dbo.InvoiceItems.Name AS InvoiceItemName,
dbo.Companies.Name AS CompanyName, dbo.InvoiceTypes.Name AS InvoiceTypeName
FROM dbo.Invoices LEFT OUTER JOIN
dbo.Companies ON dbo.Invoices.CompanyID = dbo.Companies.CompanyID LEFT OUTER JOIN
dbo.InvoiceTypes ON dbo.Invoices.InvoiceTypeID = dbo.InvoiceTypes.InvoiceTypeID LEFT OUTER JOIN
dbo.InvoiceVsInvoiceItems ON dbo.Invoices.InvoiceID = dbo.InvoiceVsInvoiceItems.InvoiceID LEFT OUTER JOIN
dbo.InvoiceItems ON dbo.InvoiceVsInvoiceItems.InvoiceVsInvoiceItemID = dbo.InvoiceItems.InvoiceItemID LEFT OUTER JOIN
dbo.Vessels ON dbo.Invoices.VesselID = dbo.Vessels.VesselID WHERE
dbo.Invoices.IsDeleted != 1
and dbo.Vessels.IsDeleted != 1
and dbo.Companies.IsDeleted != 1 '
SET FMTONLY OFF
IF #InvoiceItemID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.InvoiceItems.InvoiceItemID= ''' + CAST(#InvoiceItemID AS NVARCHAR(50)) + ''''
END
IF #InvoiceTypeID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceTypeID= ''' + CAST(#InvoiceTypeID AS NVARCHAR(50)) + ''''
END
IF #VesselID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.VesselID= ''' + CAST(#VesselID AS NVARCHAR(50)) + ''''
END
IF #PaidBy IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + 'AND dbo.Invoices.PaidBy = ''' + CAST(#PaidBy AS NVARCHAR(50)) + ''''
END
IF #InvoiceNo IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + 'AND dbo.Invoices.InvoiceNo = ''' + CAST(#InvoiceNo AS NVARCHAR(50)) + ''''
END
IF #CompanyID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.CompanyID = ''' + CAST(#CompanyID AS NVARCHAR(50)) + ''''
END
IF #FromAmount IS NOT NULL AND #ToAmount IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.Amount BETWEEN ''' + CAST(#FromAmount AS NVARCHAR(100)) + ''' AND ''' + CAST(#ToAmount AS NVARCHAR(100)) + ''''
END
IF #DueDateType IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + 'AND dbo.Invoices.DueDateType = ''' + CAST(#DueDateType AS NVARCHAR(50)) + ''''
END
IF #InvoiceFromDate IS NOT NULL AND #InvoiceToDate IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceDate Between ''' + CAST(#InvoiceFromDate AS NVARCHAR(100)) + ''' AND ''' + CAST(#InvoiceToDate AS NVARCHAR(100)) + ''''
END
IF #FromDueDate IS NOT NULL AND #ToDueDate IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.DueDate Between ''' + CAST(#FromDueDate AS NVARCHAR(100)) + ''' AND ''' + CAST(#ToDueDate AS NVARCHAR(100)) + ''''
END
EXECUTE (#SQLQuery)
END
and end question
my table date type : date format but
server shows it like datetime how can I do to change it to date format..
thank you
regards
ALTER PROCEDURE [dbo].[spGetInvoiceDetailSearch] #InvoiceItemID INT
,#InvoiceTypeID INT
,#VesselID INT
,#PaidBy NVARCHAR(50)
,#InvoiceNo NVARCHAR(50)
,#CompanyID INT
,#InvoiceFromDate DATE
,#InvoiceToDate DATE
,#FromDueDate DATE
,#ToDueDate DATE
,#FromAmount DECIMAL(18, 4)
,#ToAmount DECIMAL(18, 4)
,#DueDateType NVARCHAR(50)
AS
BEGIN
DECLARE #SQLQuery AS NVARCHAR(4000)
SELECT #SQLQuery =
'SELECT dbo.Invoices.InvoiceID, dbo.Invoices.CompanyID, dbo.Invoices.VesselID, dbo.Invoices.InvoiceNo, dbo.Invoices.DueDate, dbo.Invoices.Amount,
dbo.Invoices.Comment, dbo.Invoices.IsPaid, dbo.Invoices.PaymentDate, dbo.Invoices.PaidBy, dbo.Invoices.Period, dbo.Invoices.InvoiceDate,
dbo.Invoices.InvoiceCurrencyCode, dbo.Invoices.InvoiceAmount, dbo.Invoices.IsReceived, dbo.Invoices.IsProforma, dbo.Invoices.InvoiceTypeID,
dbo.Invoices.IsDeleted, dbo.Invoices.Parity, dbo.Invoices.DueDateType, dbo.Vessels.Name AS VesselName, dbo.InvoiceVsInvoiceItems.ItemPrice as ItemPrice,
dbo.InvoiceVsInvoiceItems.InvoiceItemID as InvoiceItemID, dbo.InvoiceVsInvoiceItems.VAT as VAT, dbo.InvoiceVsInvoiceItems.ItemType as ItemType, dbo.InvoiceItems.Name AS InvoiceItemName,
dbo.Companies.Name AS CompanyName, dbo.InvoiceTypes.Name AS InvoiceTypeName
FROM dbo.Invoices LEFT OUTER JOIN
dbo.Companies ON dbo.Invoices.CompanyID = dbo.Companies.CompanyID LEFT OUTER JOIN
dbo.InvoiceTypes ON dbo.Invoices.InvoiceTypeID = dbo.InvoiceTypes.InvoiceTypeID LEFT OUTER JOIN
dbo.InvoiceVsInvoiceItems ON dbo.Invoices.InvoiceID = dbo.InvoiceVsInvoiceItems.InvoiceID LEFT OUTER JOIN
dbo.InvoiceItems ON dbo.InvoiceVsInvoiceItems.InvoiceVsInvoiceItemID = dbo.InvoiceItems.InvoiceItemID LEFT OUTER JOIN
dbo.Vessels ON dbo.Invoices.VesselID = dbo.Vessels.VesselID WHERE
dbo.Invoices.IsDeleted != 1
and dbo.Vessels.IsDeleted != 1
and dbo.Companies.IsDeleted != 1 '
SET FMTONLY OFF
IF #InvoiceItemID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.InvoiceItems.InvoiceItemID= ' + CAST(#InvoiceItemID AS NVARCHAR(50)) + ''
END
IF #InvoiceTypeID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceTypeID= ' + CAST(#InvoiceTypeID AS NVARCHAR(50)) + ''
END
IF #VesselID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.VesselID= ' + CAST(#VesselID AS NVARCHAR(50)) + ''
END
IF #PaidBy IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.PaidBy = ''' + CAST(#PaidBy AS NVARCHAR(50)) + ''''
END
IF #InvoiceNo IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceNo = ''' + CAST(#InvoiceNo AS NVARCHAR(50)) + ''''
END
IF #CompanyID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.CompanyID = ' + CAST(#CompanyID AS NVARCHAR(50)) + ''
END
IF #FromAmount IS NOT NULL AND #ToAmount IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.Amount BETWEEN ''' + CAST(#FromAmount AS NVARCHAR(100)) + ''' AND ''' + CAST(#ToAmount AS NVARCHAR(100)) + ''''
END
IF #DueDateType IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.DueDateType = ''' + CAST(#DueDateType AS NVARCHAR(50)) + ''''
END
IF #InvoiceFromDate IS NOT NULL AND #InvoiceToDate IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceDate Between ''' + CAST(#InvoiceFromDate AS NVARCHAR(100)) + ''' AND ''' + CAST(#InvoiceToDate AS NVARCHAR(100)) + ''''
END
IF #FromDueDate IS NOT NULL AND #ToDueDate IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.DueDate Between ''' + CAST(#FromDueDate AS NVARCHAR(100)) + ''' AND ''' + CAST(#ToDueDate AS NVARCHAR(100)) + ''''
END
PRINT (#SQLQuery)
END
First of all, debugging it's very easy. Replace EXEC(#SQLQUery) with print and then you see your actual query.
You had some sintax error ( some places where AND was missing a space in front) and also you have some interger that were treated as strings.
Try my updated procedure.
It seems that procedure is getting called properly but no rows are getting returned, to debug the exact problem you can write actual hardcoded query returning 1 or more records instead of dynamic query.
So after doing that there are two possibilities
procedure call via edmx returns data, that means parameter values are causing some problem.
Any Data is not returned.
To solve any of the problem you need to check corresponding sql query which is getting generated while calling SP via Enitity Framework.

SQL Server 2012 Dynamic Query calling from Functions return

I have a scalar-valued [return type nvarchar] function that returns a dynamic Query String.
Let my Function is like following …
CREATE FUNCTION ABC
(
)
RETURNS nvarchar(MAX)
AS
BEGIN
return 'Select * from Table1'
END
I want to Execute it like following …
Select * from dbo.ABC()
Or
Select * from EXEC(dbo.ABC())
Is That possible in SQL Server 2012?
I have to do it without using openquery.
-- My Actual Function --
ALTER FUNCTION [dbo].[RowToColumn]
(
-- Add the parameters for the function here
)
RETURNS nvarchar(MAX)
AS
BEGIN
DECLARE #PunchList nvarchar(MAX)
DECLARE #PunchListTOP nvarchar(MAX)
DECLARE #SQL nvarchar(MAX)
DECLARE #Flag INT
SET #PunchList = ''
SET #PunchListTOP = ''
DECLARE #I INT
SET #Flag = (select MAX(X) as MMAX from (select Employee_ID,Date_Of_Working, count(Date_Of_Working) as X from DataInOneRowStep3 group by Date_Of_Working ,Employee_ID ) A)
Set #I =1
WHILE (#I<= #Flag)
BEGIN
if (#PunchList = '' )
BEGIN
Set #PunchList = 'Punch_' + CONVERT(varchar, #I)
Set #PunchListTOP = ' MAX(Punch_' + CONVERT(varchar, #I) +') Punch_' + CONVERT(varchar, #I)
END
else
BEGIN
Set #PunchList = #PunchList + ',' + 'Punch_' + CONVERT(varchar, #I)
Set #PunchListTOP =#PunchListTOP +','+ ' MAX(Punch_' + CONVERT(varchar, #I) +') Punch_' + CONVERT(varchar, #I)
END
SET #I = #I + 1
END
SET #SQL ='SELECT Employee_Id,Date_OF_Working,Shift_Id,'+#PunchListTOP+' FROM (
SELECT * from DataInOneRowStep4
) as s
PIVOT
(
MAX(EntryTime)
FOR Punch IN ('+#PunchList+')
)AS piv group by Employee_Id,Date_OF_Working,Shift_Id'
RETURN #SQL
END

Msg 137, Level 15, State 2, Line 29 Must declare the scalar variable "#ACTIVE_STATUS"

ALTER PROCEDURE [dbo].[S_EDIT_USER] (#DSA_CODE VARCHAR(10),
#REQUESTOR_DEPT VARCHAR(40),
#ACTIVE_STATUS INT,
#MAKER_ID VARCHAR(10),
#MAKER_IP VARCHAR(20),
#ERROR_CODE INT OUTPUT)
AS
BEGIN
DECLARE #CNT INT;
DECLARE #SQL NVARCHAR(MAX);
SELECT #CNT = COUNT(*)
FROM TMAS_UAM_USER_TMP
WHERE DSA_CODE = #DSA_CODE;
IF #CNT > 0
SET #ERROR_CODE = 1;
ELSE
SET #ERROR_CODE = 0;
IF #REQUESTOR_DEPT = 'N'
SET #REQUESTOR_DEPT = '';
ELSE
SET #REQUESTOR_DEPT = #REQUESTOR_DEPT;
PRINT #REQUESTOR_DEPT;
IF #ERROR_CODE = 0
SET #SQL = 'INSERT INTO TMAS_UAM_USER_TMP (
DSA_CODE
,DSA_NAME
,DSA_CITY
,DSA_PRODUCT
,DSA_PHNO
,DSA_MOBNO
,DSA_RQSTR
,DSA_RQSTR_DEPT
,GROUP_ID
,ACTIVE_STATUS
,REQ_TYPE
,LAST_LOGED_IN
,CREATED_ID
,CREATED_IP
,CREATED_DATE
,MAKER_ID
,MAKER_IP
,MAKER_DATE
) SELECT DSA_COD
,DSA_NAM
,DSA_CTY
,PRODUCT
,DSA_PHO
,DSA_MOB
,REQUESTOR
,' + #REQUESTOR_DEPT + '
,GROUP_ID
,#ACTIVE_STATUS
,1
,LAST_LOG_DAT
,CREATED_ID
,CREATED_IP
,CREATED_DATE
,' + #MAKER_ID + '
,' + #MAKER_IP + '
,GETDATE()
FROM DSA_MST WHERE DSA_COD = ' + #DSA_CODE + ' and ';
IF #REQUESTOR_DEPT = 'N'
BEGIN
SET #SQL = #SQL + 'REQUESTOR_DEPT is null';
PRINT( 'If Query' + #SQL );
END
ELSE
BEGIN
SET #SQL = #SQL + 'REQUESTOR_DEPT = ''' + #REQUESTOR_DEPT + '''';
PRINT( 'Else Query' + #SQL );
END
EXECUTE (#SQL);
RETURN #ERROR_CODE;
END
The outer variables and parameters are not in scope for your EXECUTE (#SQL);
You need to use sp_executesql instead and pass them in as parameters.
Also you should read up on SQL injection. You might be vulnerable if parameters such as #REQUESTOR_DEPT originate from untrusted sources such as user input as you are just concatenating them straight into the query.

Conversion failed when converting date and/or time from character string?

I use pivot table but when I execute I got this error please help me I am stuck on this thanks in advance sorry if any mistake and please also tell me that how to handle string in string in sql server I use " '' '',''-'' " but not sure it is correct or not please help me as soon as posible here are the query
SELECT #SQL = 'SELECT '
WHile #I <= #Months
BEGIN
SET #YearMonth = REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, DateAdd(Month, #I, #StartDate), 13), 3,9)), ' ', '-')
SET #ColumnText = #YearMonth
SET #SQL = #SQL + 'ISNULL([' + #YearMonth + '], 0.00) as ''' + #ColumnText + ''','
SET #I = #I +1
END
Set #I = 0
SET #SQL = #SQL + 'Product,Supplier,PackPrice,QuantityInPack,Code,SupplierID,Description,RebateAmount
FROM
(
SELECT p.NAME AS product,p.Code AS Code,P.Description as Description,oi.PackPrice,oi.QuantityInPack AS Packsize,S.ID AS SupplierID,s.[Name] AS Supplier,
CASE when oi.RebateType=2 then (oi.PackPrice*oi.RebateAmount)/100 ELSE oi.RebateAmount END AS RebateAmount ,o.Total as TotalSale,
REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, O.CreatedDate, 13), 3,9)), '' '',''-'') as tdate
FROM dbo.SCM_Product p WITH (NOLOCK)
INNER JOIN SCM_OrderItem oi WITH (NOLOCK) ON oi.ProductId = p.ID
LEFT OUTER JOIN dbo.SCM_Supplier s WITH(NoLock) ON oi.SupplierID=s.ID
LEFT OUTER JOIN SCM_Order o WITH (NOLOCK) ON o.Id = oi.ProductId AND O.Status <> 5 -- CANCELLED
AND O.Deleted = 0
WHERE ('''+#SupplierID+''' IS NULL OR s.ID IN (SELECT * FROM GetIDsTableFromIDsList(#SupplierID)))
AND ('''+#ProductID+''' IS NULL OR p.ID IN (SELECT * FROM GetIDsTableFromIDsList(#ProductID)) )
AND (o.CreatedDate >= '''+ dbo.GetDatePart(#StartDate) +''' AND o.CreatedDate <= '''+ dbo.GetDatePart(#Enddate) +''')
GROUP BY REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, o.CreatedDate, 13), 3,9)), '' '',''-''),
s.ID,p.Code,p.NAME,s.NAME,P.Description,oi.packPrice,oi.QuantityInPack,oi.RebateAmount,oi.RebateType,oi.PackPrice,o.Total
) SD
PIVOT
( SUM( SD.TotalSale) FOR SD.tdate IN ('
WHile #I <= #Months
BEGIN
SET #YearMonth = REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, DateAdd(Month, #I, #StartDate), 13), 3,9)), ' ', '-')
IF #I = #Months
BEGIN
SET #SQL = #SQL + ' [' + #YearMonth + ']'
END
ELSE
BEGIN
SET #SQL = #SQL + ' [' + #YearMonth + '],'
END
SET #I = #I +1
END
SET #SQL = #SQL + ')) as pvt
ORDER BY Supplier '
--EXEC(#SQL)
PRINT #SQL
The easiest way of doing it would be to use QUOTENAME() function,because you could easily miss quote in a large query.
Example:
DECLARE #name AS CHAR(10) = 'Revolver'
DECLARE #sql as NVARCHAR(300) = 'SELECT *
FROM Music.Album
WHERE Name ='+ QUOTENAME(#name,'''')
PRINT #sql;
or
DECLARE #name AS CHAR(10) = 'Revolver'
DECLARE #sql as NVARCHAR(300) = 'SELECT *
FROM Music.Album
WHERE Name ='''+ #name + ''''
PRINT #sql;

Resources