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 )
Related
I have a stored procedure where I am trying to update a column with the content of #Value.
This is my stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [PowerApp].[UpdateTableRequestSingle]
(#Solution nvarchar(100),
#ColumnName nvarchar(100),
#Value nvarchar(255),
#Record nvarchar(100),
#CreatedBy nvarchar(50),
#ExecutionFlag nvarchar(1))
AS
BEGIN
DECLARE #CRLF VARCHAR(2) = CHAR(13) + CHAR(10) --Linebreak
DECLARE #SQLStatement VARCHAR(MAX)
SET #SQLStatement = 'UPDATE [Extract' + #Solution + '].[TableRequest]' + #CRLF +
'SET [' + #ColumnName + '] = ' + '''' + #Value + '''' + #CRLF +
'WHERE TableName = ' + '''' + #Record + ''''
DECLARE #SQLStatementHistoryLog VARCHAR(MAX)
SET #SQLStatementHistoryLog = 'INSERT INTO [Extract' + #Solution + '].[TableRequestHistoryLog] ([SQLStatement], [CreatedBy])' + #CRLF +
'VALUES(''' + REPLACE(#SQLStatement,'''','''''') + ''',''' + #CreatedBy + ''')'
IF #ExecutionFlag = '0'
BEGIN
PRINT #SQLStatement
PRINT #SQLStatementHistoryLog
END
IF #ExecutionFlag = '1'
BEGIN
BEGIN TRANSACTION;
EXEC (#SQLStatement)
EXEC (#SQLStatementHistoryLog)
COMMIT TRANSACTION;
END
END;
And I am executing it with this:
/*
[PowerApp].[UpdateTableRequestSingle]
#Solution = 'SF',
#ColumnName = 'TableDataRequestWhereCustomDescription',
#Value = 'CRM_CP_Owner_Company_Number__c IN ('190', '230', '440', '450', '480')',
#Record = 'Account',
#CreatedBy = 'DKRAH',
#ExecutionFlag = 1
*/
If I pass
#Value = 'CRM_CP_Owner_Company_Number__c IN (190, 230, 440, 450, 480)'
it works but I want it to work with
#Value='CRM_CP_Owner_Company_Number__c IN ( '190', '230', '440', '450', '480')'
Does anyone know how to edit the T-SQL to make it work.
You don't escape the single quotes in #Value and therefore end up with unescaped single quotes in you dynamic query.
You should use parameterization using sp_executesql. You should also use quotename() to get the correctly quoted identifiers.
...
SET #SQLStatement =
'UPDATE ' + quotename('Extract' + #Solution) + '.[TableRequest]' + #CRLF +
'SET ' + quotename(#ColumnName) + ' = #Value' + #CRLF +
'WHERE TableName = #Record';
...
EXECUTE sp_executesql #SQLStatement, '#Value nvarchar(255), #Record nvarchar(255)', #Value = #Value, #Record = #Record;
...
(And analog for #SQLStatementHistoryLog)
for #ColumnName and maybe even #Solution you should better use the type sysname which is the type for identifiers.
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)
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
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.
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.