How to display no Data message in Stored procedre - sql-server

If #MeasureRuleTrendId value has no data i need to display either empty table or No Data message.. Can you please help what we need to add in the below code... Thanks in Advance
ALTER PROCEDURE [dbo].[uspRptDQMeasureDetail] (#MeasureRuleTrendId INT)
AS
BEGIN
SET NOCOUNT ON
truncate table dq.tt
IF OBJECT_ID('tempdb..#columns') IS NOT NULL
DROP TABLE #columns
IF OBJECT_ID('tempdb..##Tmp') IS NOT NULL
DROP TABLE ##Tmp
CREATE TABLE #Columns (
Id INT IDENTITY
,Col VARCHAR(500)
)
DECLARE #RowsToProcess AS INT
DECLARE #CurrentRow AS INT
DECLARE #SQL AS VARCHAR(MAX)
DECLARE #xml AS XML
DECLARE #Col AS VARCHAR(100)
DECLARE #SQLUnpivot AS VARCHAR(MAX)
DECLARE #SQLTempTable AS VARCHAR(MAX)
SELECT #xml = DetailCSV
FROM DQ.MeasureRuleDtl
WHERE [MeasureRuleTrendId] = #MeasureRuleTrendId
SET #SQL = 'DECLARE #xml AS XML; SELECT #xml = DetailCSV
FROM DQ.MeasureRuleDtl where[MeasureRuleTrendId] = ' + Convert(VARCHAR(100), #MeasureRuleTrendId) + '; INSERT INTO ##Tmp Select '
SET #SQLUnpivot = 'SELECT ID, ColName, VAL FROM (SELECT * from ##Tmp ) p UNPIVOT (VAL FOR ColName IN ('
SET #SQLTempTable = ''
SET #SQLTempTable = 'CREATE Table ##Tmp ( ID INT Identity ,'
INSERT INTO #Columns (col)
SELECT DISTINCT C.value('local-name(.)', 'varchar(50)') AS NodeName
FROM #xml.nodes('/row/*') AS T(C)
SET #RowsToProcess = ##ROWCOUNT
SET #CurrentRow = 0
WHILE #CurrentRow < #RowsToProcess
BEGIN
SET #CurrentRow = #CurrentRow + 1
SELECT #Col = Col
FROM #Columns
WHERE ID = #CurrentRow
SET #sql = #SQL + #col + ' = Events.value(' + '''' + '(' + #col + ')[1]' + '''' + ',' + '''' + 'varchar(max)' + '''' + ')'
SET #SQLTempTable = #SQLTempTable + #Col + ' VARCHAR(max)'
SET #SQLUnpivot = #SQLUnpivot + #Col
IF #CurrentRow = #RowsToProcess
BEGIN
SET #sql = #sql + ' '
SET #SQLTempTable = #SQLTempTable + ' '
SET #SQLUnpivot = #SQLUnpivot + ' '
END
ELSE
BEGIN
SET #sql = #sql + ' , '
SET #SQLTempTable = #SQLTempTable + ' , '
SET #SQLUnpivot = #SQLUnpivot + ' , '
END
END
SET #SQL = #sql + + ' FROM #xml.nodes(''/row'') AS XTbl(Events)'
SET #SQLUnpivot = #SQLUnpivot + '))AS unpvt'
set #SQLUnpivot = 'insert into dq.tt ' + #SQLUnpivot
SET #SQLTempTable = #SQLTempTable + ')'
EXECUTE (#SQLTempTable)
EXECUTE (#SQL)
Print #sqlunpivot
EXECUTE (#SQLUnpivot)
SELECT * from dq.tt
SET NOCOUNT OFF
END

It should be enough to add this in your final WHERE, if this is a question of performance, you could add the WHERE to your dynamic SQL too:
ALTER PROCEDURE [dbo].[uspRptDQMeasureDetail] (#MeasureRuleTrendId INT)
AS
BEGIN
SET NOCOUNT ON
truncate table dq.tt
IF OBJECT_ID('tempdb..#columns') IS NOT NULL
DROP TABLE #columns
IF OBJECT_ID('tempdb..##Tmp') IS NOT NULL
DROP TABLE ##Tmp
CREATE TABLE #Columns (
Id INT IDENTITY
,Col VARCHAR(500)
)
DECLARE #RowsToProcess AS INT
DECLARE #CurrentRow AS INT
DECLARE #SQL AS VARCHAR(MAX)
DECLARE #xml AS XML
DECLARE #Col AS VARCHAR(100)
DECLARE #SQLUnpivot AS VARCHAR(MAX)
DECLARE #SQLTempTable AS VARCHAR(MAX)
SELECT #xml = DetailCSV
FROM DQ.MeasureRuleDtl
WHERE [MeasureRuleTrendId] = #MeasureRuleTrendId
SET #SQL = 'DECLARE #xml AS XML; SELECT #xml = DetailCSV
FROM DQ.MeasureRuleDtl where[MeasureRuleTrendId] = ' + Convert(VARCHAR(100), #MeasureRuleTrendId) + '; INSERT INTO ##Tmp Select '
SET #SQLUnpivot = 'SELECT ID, ColName, VAL FROM (SELECT * from ##Tmp ) p UNPIVOT (VAL FOR ColName IN ('
SET #SQLTempTable = ''
SET #SQLTempTable = 'CREATE Table ##Tmp ( ID INT Identity ,'
INSERT INTO #Columns (col)
SELECT DISTINCT C.value('local-name(.)', 'varchar(50)') AS NodeName
FROM #xml.nodes('/row/*') AS T(C)
SET #RowsToProcess = ##ROWCOUNT
SET #CurrentRow = 0
WHILE #CurrentRow < #RowsToProcess
BEGIN
SET #CurrentRow = #CurrentRow + 1
SELECT #Col = Col
FROM #Columns
WHERE ID = #CurrentRow
SET #sql = #SQL + #col + ' = Events.value(' + '''' + '(' + #col + ')[1]' + '''' + ',' + '''' + 'varchar(max)' + '''' + ')'
SET #SQLTempTable = #SQLTempTable + #Col + ' VARCHAR(max)'
SET #SQLUnpivot = #SQLUnpivot + #Col
IF #CurrentRow = #RowsToProcess
BEGIN
SET #sql = #sql + ' '
SET #SQLTempTable = #SQLTempTable + ' '
SET #SQLUnpivot = #SQLUnpivot + ' '
END
ELSE
BEGIN
SET #sql = #sql + ' , '
SET #SQLTempTable = #SQLTempTable + ' , '
SET #SQLUnpivot = #SQLUnpivot + ' , '
END
END
SET #SQL = #sql + + ' FROM #xml.nodes(''/row'') AS XTbl(Events)'
SET #SQLUnpivot = #SQLUnpivot + '))AS unpvt'
set #SQLUnpivot = 'insert into dq.tt ' + #SQLUnpivot
SET #SQLTempTable = #SQLTempTable + ')'
EXECUTE (#SQLTempTable)
EXECUTE (#SQL)
Print #sqlunpivot
EXECUTE (#SQLUnpivot)
--Added your parameter with WHERE...
SELECT * from dq.tt WHERE #MeasureRuleTrendId IS NOT NULL
SET NOCOUNT OFF
END

Related

Msg 156, Levl 15, State 1, Line 1 Incorrect syntax near keyword 'top'

This section of my code is failing. I cannot figure out why I am receiving this message. Can anyone please look it over and see if you see anything that looks wrong?
Thanks so much!!!
declare #ReportOrder int
declare #numrows int
declare #Section varchar(30)
declare #Dept_Op varchar(5)
declare #Dept varchar(30)
declare #SDept_Op varchar(5)
declare #SDept varchar(30)
declare #Class_Op varchar(5)
declare #Class varchar(30)
declare #Over_POS Int
declare #year int
declare #week int
declare #Perc_To_Total float
declare #Perc_Remaining float
declare #LS smalldatetime
declare #LYCARD_2NC smalldatetime
declare #sql nvarchar(4000)
select #year = datepart(yy,getdate())
select #year = #year - 1
select #week = staging.dbo.fn_Calendar_Week(getdate())
select #LS = staging.dbo.fn_Last_Saturday(getdate())
select #lyCARD_2NC = dateadd(yy,-1,#LS)
Truncate table ReportData.dbo.rpt_Holiday_Top_Selling_Report_2NC
Truncate table Staging.dbo.tmp_Top10_2NC
declare cur cursor for select ReportOrder, numrows, Section, Dept_Op, Dept, SDept_Op, SDept, Class_Op, Class, Over_POS
from Reference.dbo.Holiday_Top_Selling_Config_new
order by ReportOrder
open cur
fetch next from cur into #ReportOrder, #numrows, #Section, #Dept_Op, #Dept, #SDept_Op, #SDept, #Class_Op, #Class, #Over_POS
while ##Fetch_Status = 0
begin
select #sql = 'insert into Reportdata.dbo.rpt_Holiday_Top_Selling_Report_2NC '
select #sql = #sql + 'select top ' + cast(#numrows as char(2)) + ' '
select #sql = #sql + cast(#ReportOrder as char(3)) + ' as PrintOrder,'
select #sql = #sql + '''' + #Section + '''' + ' as Section,'
select #sql = #sql + ' row_Number() over (order by t1.wtd_dollars desc) as Rank, '
select #sql = #sql + ' t1.ISBN as TY_ISBN, '
select #sql = #sql + ' t1.title as TY_Title, '
select #sql = #sql + ' t1.Author as TY_Author, '
select #sql = #sql + ' t1.Dept as TY_Dept_Num, '
select #sql = #sql + ' t1.SDept as TY_SDept_Num, '
select #sql = #sql + ' t1.Class as TY_Class_Num, '
select #sql = #sql + ' t1.display_min, '
select #sql = #sql + ' t1.Class_Name as TY_Class, '
select #sql = #sql + ' t1.wtd_Dollars as TY_SLS$, '
select #sql = #sql + ' t1.wtd_Units as TY_SLSU, '
select #sql = #sql + ' 0 as Discount, '
select #sql = #sql + ' t1.OnHand_2NC as OnHand, '
select #sql = #sql + ' isnull(t1.Qty_OnOrder,0) as OnOrder, '
select #sql = #sql + ' 0 as Proj, '
select #sql = #sql + ' NULL as NNTC, '
select #sql = #sql + ' NULL as LY_ISBN, '
select #sql = #sql + ' NULL as LY_Title, '
select #sql = #sql + ' NULL as LY_Author, '
select #sql = #sql + ' NULL as LY_Dept_Num, '
select #sql = #sql + ' NULL as LY_SDept_Num, '
select #sql = #sql + ' NULL as LY_Class_Num, '
select #sql = #sql + ' NULL as LY_On_Hand, '
select #sql = #sql + ' NULL as LY_Class, '
select #sql = #sql + ' NULL as LY_SLS$, '
select #sql = #sql + ' NULL as LY_SLSU, '
select #sql = #sql + ' NULL as Forecast_Thru, '
select #sql = #sql + ' NULL as Week_42, '
select #sql = #sql + ' NULL as Week_43, '
select #sql = #sql + ' NULL as Week_44, '
select #sql = #sql + ' NULL as Week_45, '
select #sql = #sql + ' NULL as Week_46, '
select #sql = #sql + ' NULL as Week_47, '
select #sql = #sql + ' NULL as Week_48, '
select #sql = #sql + ' NULL as Week_49 '
select #sql = #sql + ' from dssdata.dbo.CARD_2NC t1'
select #sql = #sql + ' where t1.dept ' + #Dept_Op + ' ' + #Dept
select #sql = #sql + ' and t1.SDept ' + #SDept_Op + ' ' + #SDept
select #sql = #sql + ' and t1.Class ' + #Class_Op + ' ' + #Class
if #Over_POS > 0
select #sql = #sql + ' and t1.Retail > ' + cast(#Over_POS as char(3)) + ' '
select #sql = #sql + ' order by wtd_Dollars desc '
EXEC sp_executesql #sql
select #sql = 'insert into Staging.dbo.tmp_Top10_2NC'
select #sql = #sql + 'select top ' + cast(#numrows as char(3)) + ' '
select #sql = #sql + 'row_Number() over (order by t1.LYWeek1dollars desc) as LYRank, '
select #sql = #sql + 't1.ISBN as ISBN, '
select #sql = #sql + 't1.Title as Title, '
select #sql = #sql + 't1.Author, '
select #sql = #sql + 't1.Dept, '
select #sql = #sql + 't1.SDept, '
select #sql = #sql + 't1.Class, '
select #sql = #sql + 't1.OnHand_2NC, '
select #sql = #sql + 't1.Class_Name, '
select #sql = #sql + 't1.LYWeek1Dollars as Sls$, '
select #sql = #sql + 't1.LYWeek1Units as SlsU '
select #sql = #sql + 'from dssdata.dbo.CARD_2NC t1 '
select #sql = #sql + ' where t1.dept ' + #Dept_Op + ' ' + #Dept
select #sql = #sql + ' and t1.SDept ' + #SDept_Op + ' ' + #SDept
select #sql = #sql + ' and t1.Class ' + #Class_Op + ' ' + #Class
if #Over_POS > 0
select #sql = #sql + ' and t1.retail > ' + cast(#Over_POS as char(3)) + ' '
select #sql = #sql + ' order by LYWeek1Dollars desc '
EXEC sp_executesql #sql
select #sql = 'update ReportData.dbo.rpt_Holiday_Top_Selling_Report_2NC '
select #sql = #sql + 'Set LY_Title = Title, '
select #sql = #sql + 'LY_ISBN = ISBN, '
select #sql = #sql + 'NNTC = (Proj + (TY_SLSU * 3)) - (ReportData.dbo.rpt_Holiday_Top_Selling_Report_2NC.onHand + OnOrder), '
select #sql = #sql + 'LY_Author = Author, '
select #sql = #sql + 'LY_Dept_Num = Dept_Num, '
select #sql = #sql + 'LY_SDept_Num = SDept_Num, '
select #sql = #sql + 'LY_Class_Num = Class_Num, '
select #sql = #sql + 'LY_OnHand = Staging.dbo.tmp_Top10_2NC.OnHand, '
select #sql = #sql + 'LY_Class = Class, '
select #sql = #sql + 'LY_SLS$ = SLS$, '
select #sql = #sql + 'LY_SLSU = SLSU '
select #sql = #sql + 'from Staging.dbo.tmp_Top10_2NC'
select #sql = #sql + 'where Staging.dbo.tmp_Top10_2NC.LYRank = Rank '
select #sql = #sql + 'and Section = ' + '''' + #Section + ''''
EXEC sp_executesql #sql
truncate table Staging.dbo.tmp_Top10_NEW
fetch next from cur into #ReportOrder, #numrows, #Section, #Dept_Op, #Dept, #SDept_Op, #SDept, #Class_Op, #Class, #Over_POS
end
close cur
deallocate cur
Missing a space at the end of
select #sql = 'insert into Staging.dbo.tmp_Top10_2NC'
select #sql = 'insert into Staging.dbo.tmp_Top10_2NC '
select #sql = #sql + 'select top ' + cast(#numrows as char(3)) + ' '

Assign year variable to column alias for excel sheet

I have an excel sheet which is bound to a stored procedure. In the stored procedure I am selecting the columns that appear in the excel sheet. Now I'm facing an issue when I wanted to add some more columns:
Some value 2016
Some value 2017
Some value 2018
The first column is adding the actual year to the header and the two others the next one and the year after the next one.
My problem is that I don't know how to do this dynamically. I've tried something like this:
DECLARE #actualYear INT = YEAR(GETDATE())
SELECT tab.Name,
myTable.SomeValue [Some value #actualYear],
myTableNext.SomeValue [Some value #actualYear+1],
myTableAfterTheNext.SomeValue [Some value #actualYear+2]
FROM SomeTable tab
LEFT JOIN MyTable myTable ON tab.SomeId = myTable.SomeId
AND myTable.[Year] = #actualYear
LEFT JOIN MyTable myTableNext ON tab.SomeId = myTableNext.SomeId
AND myTable.[Year] = (#actualYear+1)
LEFT JOIN MyTable myTableAfterTheNext ON tab.SomeId = myTableAfterTheNext.SomeId
AND myTable.[Year] = (#actualYear+2)
The output is the following:
+------+------------------------+--------------------------+--------------------------+
| Name | Some value #actualYear | Some value #actualYear+1 | Some value #actualYear+2 |
+------+------------------------+--------------------------+--------------------------+
Second try:
SELECT tab.Name,
myTable.SomeValue ['Some value' + #actualYear]
...
Output:
+------+----------------------------+ ...
| Name | 'Some value' + #actualYear | ...
+------+----------------------------+ ...
How can I get the correct column headers dynamically?
You'll have to create a dynamic sql query like so (short example):
declare #i int;
declare #sql nvarchar(max);
set #i = 2016;
set #sql = N'select 1 as [' + cast(#i as nvarchar) + N']';
exec(#sql);
Translated to your sql query this should be something like this:
declare #sql nvarchar(max);
declare #actualYear int = year(getdate());
set #sql = #sql + N'select tab.Name, '
set #sql = #sql + N' myTable.SomeValue [' + cast(#actualYear as nvarchar) + N'], '
set #sql = #sql + N' myTableNext.SomeValue [' + cast(#actualYear + 1 as nvarchar) + N'], '
set #sql = #sql + N' myTableAfterTheNext.SomeValue [' + cast(#actualYear + 2 as nvarchar) + N'] '
set #sql = #sql + N'from SomeTable tab '
set #sql = #sql + N'left join MyTable myTable '
set #sql = #sql + N'on tab.SomeId = myTable.SomeId '
set #sql = #sql + N' and myTable.Year = #actualYear '
set #sql = #sql + N'left join MyTable myTableNext '
set #sql = #sql + N'on tab.SomeId = myTableNext.SomeId '
set #sql = #sql + N' and myTable.Year = (#actualYear + 1) '
set #sql = #sql + N'left join MyTable myTableAfterTheNext '
set #sql = #sql + N'on tab.SomeId = myTableAfterTheNext.SomeId '
set #sql = #sql + N' and myTable.Year = (#actualYear + 2); '
exec(#sql);
How to easily convert an SQL query into a dynamic SQL query:
Note, within Notepad++ you should replace the regular expression ^(.*)$ with set #sql = #sql + N'\1 '.
Update
Possible implementation of the above into a stored procedure (short example only):
IF OBJECT_ID('procTest', 'P') IS NOT NULL
DROP PROCEDURE procTest;
GO
CREATE PROCEDURE procTest
AS
BEGIN
DECLARE #i INT;
DECLARE #sql NVARCHAR(MAX);
SET #i = 2016;
SET #sql
= N'insert into #t (Column1) VALUES (' + CAST(#i AS NVARCHAR)
+ N'); ' + N'insert into #t (Column1) '
+ N'SELECT cast(1 as nvarchar) as [' + CAST(#i AS NVARCHAR) + N']';
EXEC (#sql);
END;
GO
CREATE TABLE #t
(
Column1 NVARCHAR(MAX)
);
EXEC dbo.procTest;
SELECT *
FROM #t;
DROP TABLE #t;

Msg 102, Level 15, State 1, Line 6 Incorrect syntax near '='

I need help with my stored procedure, I kept getting this Error, but I can't find the real error.
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near '='.
My code:
DECLARE #Batch_Num_For_Sending BIGINT;
DECLARE #IPLocal NVARCHAR(15);
SET #IPLocal = (
SELECT Local_IPAddress
FROM [RFIDSync].[dbo].[RFID_LinkSetup]
WHERE Link_ID = 1
);
DECLARE #IPMain NVARCHAR(15);
SET #IPMain = (
SELECT Main_IPAddress
FROM [RFIDSync].[dbo].[RFID_LinkSetup]
WHERE Link_ID = 1
);
DECLARE #LocationProj NVARCHAR(50);
SET #LocationProj = 'Test_Project';
SET #Batch_Num_For_Sending = (
SELECT MIN(Batch_Id)
FROM [db].[dbo].[LOCALBATCH]
WHERE Batch_Status = 0
)
SELECT #Batch_Num_For_Sending
EXEC (
'
SELECT Sync_Batch_Num FROM OPENQUERY([' + #IPMain + '\SQLEXPRESS], ''SELECT Sync_Batch_Num
FROM [db].[dbo].[SYNCBATCH] WHERE [Location] = ''''' + #LocationProj + '''''
'')
WHERE Sync_Batch_Num = ' + #Batch_Num_For_Sending + '
'
)
The below solution should add the missing ' :
DECLARE #SQL NVARCHAR(MAX) = 'SELECT Sync_Batch_Num FROM OPENQUERY([' + #IPMain + '\SQLEXPRESS], ''SELECT Sync_Batch_Num
FROM [db].[dbo].[SYNCBATCH] WHERE [Location] = ''''' + CONVERT(NVARCHAR(50), #LocationProj) + ''''''')
WHERE Sync_Batch_Num = ' + CONVERT(NVARCHAR(50), #Batch_Num_For_Sending) + '';
PRINT #SQL
EXEC (#SQL)
Try printing the result query next time to detect the error.
Your query may be ending up with different quotation marks than it is required.
Assign the dynamic sql to a variable first and see it output before passing it on to the EXEC() statement.
try the below one
DECLARE #Batch_Num_For_Sending bigint;
DECLARE #IPLocal nvarchar(15);
SET #IPLocal = (SELECT Local_IPAddress FROM [RFIDSync].[dbo].[RFID_LinkSetup] WHERE Link_ID = 1);
DECLARE #IPMain nvarchar(15);
SET #IPMain = (SELECT Main_IPAddress FROM [RFIDSync].[dbo].[RFID_LinkSetup] WHERE Link_ID = 1);
DECLARE #LocationProj nvarchar(50); SET #LocationProj = 'Test_Project';
DECLARE #SQ VARCHAR(4) = ''''
DECLARE #SQL VARCHAR(max) = ''
SET #Batch_Num_For_Sending = (SELECT MIN(Batch_Id) FROM [db].[dbo].[LOCALBATCH] WHERE Batch_Status = 0)
SELECT #Batch_Num_For_Sending
SET #SQL = 'SELECT Sync_Batch_Num FROM OPENQUERY(['+#IPMain+'\SQLEXPRESS],' + #SQ + 'SELECT Sync_Batch_Num
FROM [db].[dbo].[SYNCBATCH] WHERE [Location] =' + #SQ + #LocationProj+#SQ + ')
WHERE Sync_Batch_Num = '+CAST(#Batch_Num_For_Sending AS VARCHAR)
EXEC(#SQL)

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.

How can I make this IF statement skip to another if statement?

How can i make this If statement to skip to the below if statement? I tried else if,then, but it doesnt work. I want it to display regardless of whether input is passed into the variable.
declare #sql varchar(8000)
declare #sql_where varchar(8000)
declare #ww varchar(10)
declare #plant varchar(10)
declare #plnr_id varchar(10)
set #plant = 'CS58'
set #ww = '201240'
set #plnr_id = 'G37'
set #sql_where = 'where'
set #sql = 'select * from rout_sub_doi '
if len(#plant) > 0
set #sql_where = #sql_where + ' plant = ''' + #plant + ''' '
if len(#ww) > 0
set #sql_where = #sql_where + 'AND sys_intel_ww = ''' + #ww + ''' '
if len(#plnr_id) > 0
set #sql_where = #sql_where + ' AND plnr_id = ''' + #plnr_id + ''' '
print #sql
print #sql_where
exec (#sql + #sql_where )
The common way to handle unknown number of conditions is to make the first one WHERE 1=1 or something benign such as WHERE id IS NOT NULL when id is known to be not-nullable.
declare #sql varchar(8000)
declare #sql_where varchar(8000)
declare #ww varchar(10)
declare #plant varchar(10)
declare #plnr_id varchar(10)
set #plant = 'CS58'
set #ww = '201240'
set #plnr_id = 'G37'
set #sql_where = ''
set #sql = 'select * from rout_sub_doi where 1=1 '
if len(#plant) > 0
set #sql_where = #sql_where + 'AND plant = ''' + #plant + ''' '
if len(#ww) > 0
set #sql_where = #sql_where + 'AND sys_intel_ww = ''' + #ww + ''' '
if len(#plnr_id) > 0
set #sql_where = #sql_where + 'AND plnr_id = ''' + #plnr_id + ''' '
print #sql
print #sql_where
exec (#sql + #sql_where )

Resources