What am I doing wrong? My stored procedure is not working according to need when using =, >, < as a parameter please help
Here is my stored procedure:
ALTER PROCEDURE [dbo].[storedp_Search]
#pAccountTypeId int = null,
#pFirstName varchar(25) = null,
#pLastName varchar(35) = null,
#pZip varchar(10) = null,
#pOperator varchar(2) = null,
#pRating varchar(2) = null
AS
BEGIN
SET NOCOUNT ON;
Declare #SQLQuery AS NVarchar(4000)
SET #SQLQuery = 'select
at.AccountName,
U.UserId, U.FirstName, U.LastName,
U.NMLS, U.[Address], U.PrimaryEmailId As Office,
U.AdditionalEmail As Personal,
U.DirectPhone As Work, U.Mobile,
R.RatingStar
from
[User] U
left outer join
RatingReview R on R.UserId = U.UserId
left outer join
AccountType at on at.AccountTypeId = U.AccountTypeId
where U.Deleted = 0
AND at.AccountTypeId = '+CAST(#pAccountTypeId as Varchar(10))+'
AND U.FirstName = ''' + #pFirstName + '''
AND U.LastName = ''' + #pLastName + '''
AND U.Zip = ''' + #pZip + '''
AND R.RatingStar = ''' + #pRating + ''''
IF(#pAccountTypeId != null OR #pAccountTypeId != '')
BEGIN
SET #SQLQuery = #SQLQuery + ' AND at.AccountTypeId='+CONVERT(VARCHAR, #pAccountTypeId )
END
IF(#pFirstName != null OR #pFirstName != '')
BEGIN
SET #SQLQuery=#SQLQuery+' AND U.FirstName Like ''%' + #pFirstName + '%'''
END
IF(#pLastName !=null OR #pLastName != '')
BEGIN
SET #SQLQuery=#SQLQuery+' AND U.LastName Like ''%' + #pLastName + '%'''
END
IF(#pZip !=null OR #pZip != '')
BEGIN
SET #SQLQuery=#SQLQuery+' AND U.Zip Like ''%' + #pZip + '%'''
END
IF(#pOperator = '=')
BEGIN
SET #SQLQuery += ' AND r.ratingstar = ' + CAST(#pRating AS NVARCHAR(5)) + ''
END
IF(#pOperator = '>')
BEGIN
SET #SQLQuery += ' AND r.ratingstar < ' + CAST(#pRating AS NVARCHAR(5)) + ''
END
IF(#pOperator = '<')
BEGIN
SET #SQLQuery += ' AND r.ratingstar > ' + CAST(#pRating AS NVARCHAR(5)) + ''
END
SET #SQLQuery=#SQLQuery+
'group by
at.AccountName,
U.UserId,
U.FirstName,
U.LastName,
U.NMLS,
U.[Address],
U.PrimaryEmailId,
U.AdditionalEmail,
U.DirectPhone,
U.Mobile,
R.RatingStar'
EXEC (#SQLQuery)
END
when i am using following exec statement its working fine
Execute storedp_Search 1,'Mark','Smith','48393','=','5'
but when using the same with different conditions then its not working.
Execute storedp_Search 1,'Mark','Smith','48393','>','4'
Try this,
I think you misspelled the operator inside the if condition, if i'm not wrong
ALTER PROCEDURE [dbo].[Storedp_Search] #pAccountTypeId INT =NULL,
#pFirstName VARCHAR(25)=NULL,
#pLastName VARCHAR(35)=NULL,
#pZip VARCHAR(10)=NULL,
#pOperator VARCHAR(2)=NULL,
#pRating VARCHAR(2)=NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQLQuery AS NVARCHAR(4000)
SET #SQLQuery= 'select
at.AccountName,
U.UserId,
U.FirstName,
U.LastName,
U.NMLS,
U.[Address],
U.PrimaryEmailId As Office,
U.AdditionalEmail As Personal,
U.DirectPhone As Work,
U.Mobile,
R.RatingStar
from [User] U
left outer join RatingReview R on R.UserId =U.UserId
left outer join AccountType at on at.AccountTypeId = U.AccountTypeId
where U.Deleted =0
AND at.AccountTypeId = '
+ Cast(#pAccountTypeId AS VARCHAR(10))
+ '
AND U.FirstName = ''' + #pFirstName
+ '''
AND U.LastName = ''' + #pLastName
+ '''
AND U.Zip = ''' + #pZip
+ '''
AND R.RatingStar = ''' + #pRating + ''''
IF( #pAccountTypeId IS NOT NULL
OR #pAccountTypeId != '' )
BEGIN
SET #SQLQuery=#SQLQuery + ' AND at.AccountTypeId='
+ CONVERT(VARCHAR, #pAccountTypeId )
END
IF( #pFirstName IS NOT NULL
OR #pFirstName != '' )
BEGIN
SET #SQLQuery=#SQLQuery + ' AND U.FirstName Like ''%'
+ #pFirstName + '%'''
END
IF( #pLastName IS NOT NULL
OR #pLastName != '' )
BEGIN
SET #SQLQuery=#SQLQuery + ' AND U.LastName Like ''%'
+ #pLastName + '%'''
END
IF( #pZip IS NOT NULL
OR #pZip != '' )
BEGIN
SET #SQLQuery=#SQLQuery + ' AND U.Zip Like ''%' + #pZip + '%'''
END
IF( #pOperator = '=' )
BEGIN
SET #SQLQuery += ' AND r.ratingstar = '
+ Cast(#pRating AS NVARCHAR(5)) + ''
END
IF( #pOperator = '>' )
BEGIN
SET #SQLQuery += ' AND r.ratingstar > '
+ Cast(#pRating AS NVARCHAR(5)) + ''
END
IF( #pOperator = '<' )
BEGIN
SET #SQLQuery += ' AND r.ratingstar < '
+ Cast(#pRating AS NVARCHAR(5)) + ''
END
SET #SQLQuery=#SQLQuery + 'group by
at.AccountName,
U.UserId,
U.FirstName,
U.LastName,
U.NMLS,
U.[Address],
U.PrimaryEmailId,
U.AdditionalEmail,
U.DirectPhone,
U.Mobile,
R.RatingStar'
EXEC ( #SQLQuery )
END
Related
I'm looking to change this output below. Instead of it being -999.99. I want the result to show <3.
We're wanting the Column Reported As that shows <3.0 to show on the Report and NOT -999.99.
This is the following script that I am working with:
USE [HarvestSQL]
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
ALTER PROC [dbo].[spRp20DataListData]
#date1 DATETIME,
#date2 DATETIME,
#location VARCHAR(255),
#patients NTEXT
AS
EXEC ('
SELECT
*
FROM
vwReportPortalMajorTest
WHERE
(DrawDate >= ''3/1/2006 00:00:00'') AND
(DrawDate < ''5/7/2006 00:00:00'') AND
(DrawLocation = ''Ameri-Tech Kidney Center Arlington'')
')
DECLARE #date1String VARCHAR(40)
DECLARE #date2String VARCHAR(40)
SET #date1String = CONVERT(VARCHAR(40),#date1,109)
SET #date2String = CONVERT(VARCHAR(40),#date2,109)
IF #location = 'Charleston Renal Care'
BEGIN
SET #location = 'Liberty Dialysis Petersburg'
END
EXEC ('
SELECT
*
FROM
vwRp20MajorTest
WHERE
(DrawDate >= ''' + #date1String + ''') AND
(DrawDate < ''' + #date2String + ''') AND
(DrawLocation = ''' + #location + ''')
')
Any suggestions will help me out.
Here is another Stored Procedure that may help give more details:
USE [ReportPortal]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[spRp20DataListData]
#date1 DATETIME,
#date2 DATETIME,
#location VARCHAR(1000),
#patients NTEXT,
#dynamicSqlSelectClause NTEXT,
#dynamicSqlGroupByClause NTEXT,
#suppressEmptyRows VARCHAR(10) = NULL,
#resultsToQuery INT = 0
AS
DECLARE #date1String VARCHAR(40)
DECLARE #date2String VARCHAR(40)
set #date2 = DateAdd(day, 1, #date2)
SET #date1String = CONVERT(VARCHAR(40),#date1,109)
SET #date2String = CONVERT(VARCHAR(40),#date2,109)
print #location
-- print SUBSTRING(#location,0, 7)
-- print SUBSTRING(#location,7, (len(#location)-6))
IF SUBSTRING(#location,0, 12) = 'Locations: '
BEGIN
print 'Running for Multiple Locations'
set #location = SUBSTRING(#location,12, (len(#location)-11))
print '#location updated to'
print #location
IF #resultsToQuery = 0 --All results
BEGIN
EXEC ('
SELECT
' + #dynamicSqlSelectClause + --PatientName,DrawDate,MAX((CASE WHEN NAME=''Albumin'' THEN NumberResult ELSE 0 END)) AS AlbuminResult
', PatientKey FROM
vwRp20CompletedTest
WHERE
DrawDate >= ''' + #date1String + ''' AND
DrawDate < ''' + #date2String + ''' AND
DrawAbbrev IN (' + #location + ') AND
PatientKey IN ( ' + #patients + ') AND
((NumberResult <> 0) OR (Name like ''%Hepatitis%'')) '
+ 'GROUP BY ' + #dynamicSqlGroupByClause + ', PatientKey'
)
END
ELSE
BEGIN
EXEC ('
SELECT
' + #dynamicSqlSelectClause + --PatientName,DrawDate,MAX((CASE WHEN NAME=''Albumin'' THEN NumberResult ELSE 0 END)) AS AlbuminResult
', PatientKey FROM
vwRp20MajorTest
WHERE
DrawDate >= ''' + #date1String + ''' AND
DrawDate < ''' + #date2String + ''' AND
DrawAbbrev IN (' + #location + ') AND
PatientKey IN ( ' + #patients + ') AND
((NumberResult <> 0) OR (Name like ''%Hepatitis%'')) '
+ 'GROUP BY ' + #dynamicSqlGroupByClause + ', PatientKey'
)
END
END
ELSE
BEGIN
print 'Running for Single Location'
IF #resultsToQuery = 0 --All results
BEGIN
EXEC ('
SELECT
' + #dynamicSqlSelectClause + --PatientName,DrawDate,MAX((CASE WHEN NAME=''Albumin'' THEN NumberResult ELSE 0 END)) AS AlbuminResult
', PatientKey FROM
vwRp20CompletedTest
WHERE
DrawDate >= ''' + #date1String + ''' AND
DrawDate < ''' + #date2String + ''' AND
DrawLocation = ''' + #location + ''' AND
PatientKey IN ( ' + #patients + ') ' --Ended statement here 07032019 added single quote here.
-- AND --removed all this because the number result is breaking many reports.
-- ((NumberResult > 2.9)
-- OR (Name like ''%Hepatitis%'')) '-- unsure if removing this Hepatitis will break reports.
+ 'GROUP BY ' + #dynamicSqlGroupByClause + ', PatientKey'
+ ' ORDER BY ' + #dynamicSqlGroupByClause
)
END
ELSE
BEGIN
EXEC ('
SELECT
' + #dynamicSqlSelectClause + --PatientName,DrawDate,MAX((CASE WHEN NAME=''Albumin'' THEN NumberResult ELSE 0 END)) AS AlbuminResult
' ,PatientKey FROM
vwRp20MajorTest
WHERE
DrawDate >= ''' + #date1String + ''' AND
DrawDate < ''' + #date2String + ''' AND
DrawLocation = ''' + #location + ''' AND
PatientKey IN ( ' + #patients + ') AND
((NumberResult <> 0) OR (Name like ''%Hepatitis%'')) '
+ 'GROUP BY ' + #dynamicSqlGroupByClause + ', PatientKey'
)
END
END
Would really need to see what's happening under the hood with the stored procedure. Otherwise, you would really need to modify your SELECT * statement to also include a CASE statement if "if this, then that".
Something like
USE [HarvestSQL]
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
ALTER PROC [dbo].[spRp20DataListData]
#date1 DATETIME,
#date2 DATETIME,
#location VARCHAR(255),
#patients NTEXT
AS
EXEC ('
SELECT
t.*,
CASE WHEN t.[Aluminum] < -999 THEN ''<3'' ELSE NULL END AS [Reported As]
FROM
vwRp20MajorTest t
WHERE
(t.DrawDate >= ''3/1/2006 00:00:00'') AND
(t.DrawDate < ''5/7/2006 00:00:00'') AND
(t.DrawLocation = ''Ameri-Tech Kidney Center Arlington'')
')
DECLARE #date1String VARCHAR(40)
DECLARE #date2String VARCHAR(40)
SET #date1String = CONVERT(VARCHAR(40),#date1,109)
SET #date2String = CONVERT(VARCHAR(40),#date2,109)
IF #location = 'Charleston Renal Care'
BEGIN
SET #location = 'Liberty Dialysis Petersburg'
END
EXEC ('
SELECT
*
FROM
vwRp20MajorTest
WHERE
(DrawDate >= ''' + #date1String + ''') AND
(DrawDate < ''' + #date2String + ''') AND
(DrawLocation = ''' + #location + ''')
')
https://www.w3schools.com/sql/sql_case.asp
I want to change a specific value at unknown table or column. I reached to the code helped me to search it. I found that at some tables, it's the primary column.
I must do this job because I have a lot of values that need to be changed.
I tried to do the code but I got lot of errors:
Invalid column name 'TableNameA'.
Invalid column name 'ColumnNameA'.
Hope get help as I'm still new for SQL.
What should I do?
DECLARE #SearchStrTableName nvarchar(255), #SearchStrColumnName nvarchar(255), #SearchStrColumnValue nvarchar(255), #SearchStrInXML bit, #FullRowResult bit, #FullRowResultRows int
SET #SearchStrColumnValue = '4523'
Declare #NewValueInt int = 4195403
Declare #NewValueVarChar nvarchar(20) = '4194523'
/* use LIKE syntax */
SET #FullRowResult = 1
SET #FullRowResultRows = 3
SET #SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET #SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET #SearchStrInXML = 0 /* Searching XML data may be slow */
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))
SET NOCOUNT ON
DECLARE #TableName nvarchar(256) = '',#ColumnName nvarchar(128),#ColumnType nvarchar(20), #QuotedSearchStrColumnValue nvarchar(110), #QuotedSearchStrColumnName nvarchar(110)
SET #QuotedSearchStrColumnValue = QUOTENAME(#SearchStrColumnValue,'''')
DECLARE #ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))
WHILE #TableName IS NOT NULL
BEGIN
SET #TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME LIKE COALESCE(#SearchStrTableName,TABLE_NAME)
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > #TableName
AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
)
IF #TableName IS NOT NULL
BEGIN
DECLARE #sql VARCHAR(MAX)
SET #sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(''' + #TableName + ''', 2)
AND TABLE_NAME = PARSENAME(''' + #TableName + ''', 1)
AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(#SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE #SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN #SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + #SearchStrColumnName + '''' END + ',COLUMN_NAME)'
INSERT INTO #ColumnNameTable
EXEC (#sql)
WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM #ColumnNameTable)
BEGIN
PRINT #ColumnName
SELECT TOP 1 #ColumnName = COLUMN_NAME,#ColumnType = DATA_TYPE FROM #ColumnNameTable
SET #sql = 'SELECT ''' + #TableName + ''',''' + #ColumnName + ''',' + CASE #ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + #ColumnName + ' AS nvarchar(MAX)), 4096),'''
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ #ColumnName + '),'''
ELSE 'LEFT(' + #ColumnName + ', 4096),''' END + #ColumnType + '''
FROM ' + #TableName + ' (NOLOCK) ' +
' WHERE ' + CASE #ColumnType WHEN 'xml' THEN 'CAST(' + #ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ #ColumnName + ')'
ELSE #ColumnName END + ' LIKE ' + #QuotedSearchStrColumnValue
INSERT INTO #Results
EXEC(#sql)
IF ##ROWCOUNT > 0 IF #FullRowResult = 1
BEGIN
SET #sql = 'SELECT TOP ' + CAST(#FullRowResultRows AS VARCHAR(3)) + ' ''' + #TableName + ''' AS [TableFound],''' + #ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
' FROM ' + #TableName + ' (NOLOCK) ' +
' WHERE ' + CASE #ColumnType WHEN 'xml' THEN 'CAST(' + #ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ #ColumnName + ')'
ELSE #ColumnName END + ' LIKE ' + #QuotedSearchStrColumnValue
EXEC(#sql)
DECLARE #sqlU VARCHAR(MAX)
Declare #sqlN VARCHAR(MAX)
SET #sqlU = N'UPDATE ' + quotename(#SearchStrTableName) + ' SET ' +quotename(#SearchStrColumnName)+ ' = ''' +#NewValueVarChar+ ''' WHERE ' +quotename(#SearchStrColumnName)+ ' = ''' + #SearchStrColumnValue + '''';
EXEC (#sqlU)
SET #sqlN = N'Update ' + quotename(#SearchStrTableName) + ' SET '+ quotename(#SearchStrColumnName) +'=''' +#NewValueVarChar+ '''where'+ quotename(#SearchStrColumnName) + '='+ #SearchStrColumnValue
EXEC (#sqlN)
END
DELETE FROM #ColumnNameTable WHERE COLUMN_NAME = #ColumnName
END
END
END
SET NOCOUNT OFF
IF OBJECT_ID('tempdb..#Abd_tmptbl') IS NOT NULL DROP TABLE #Abd_tmptbl
CREATE TABLE #Abd_tmptbl (TableNameA nvarchar(128), ColumnNameA nvarchar(128), ColumnValueA nvarchar(max),ColumnTypeA nvarchar(20), Count int)
INSERT INTO #Abd_tmptbl
SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results
GROUP BY TableName, ColumnName, ColumnValue, ColumnType
DECLARE #Tableee VARCHAR(20), #Columnee varchar(20), #Constraint varchar(20)
DECLARE #items TABLE(tabl int, clmn int)
Create Table #PK_tbl (PK_Col varchar (10))
WHILE EXISTS (select TOP 1 TableNameA FROM #Abd_tmptbl)
BEGIN
SELECT TOP 1 #Tableee = TableNameA, #Columnee = ColumnNameA
------------ GET All PKs of the Table ---------------------
DECLARE #PK_sql varchar(max) = N'INSERT INTO #PK_tbl(PK_Col)
(SELECT Col.Column_Name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
WHERE Col.Constraint_Name = Tab.Constraint_Name AND Col.Table_Name = Tab.Table_Name AND Constraint_Type = "PRIMARY KEY" AND Col.Table_Name = ' + #Tableee +')'
EXEC (#PK_sql)
------------------------------------------------------------
------------ GET CONTRAINT Name ----------------------------
SET #Constraint = N'SELECT name FROM sys.key_constraints WHERE type = "PK" AND OBJECT_NAME(parent_object_id) = ' + #Columnee
------------------------------------------------------------
------------ RELEASE Table From CONSTRAINTS ----------------
DECLARE #REL_tbl VARCHAR(max) = N'ALTER TABLE' + #Tableee +'DROP CONSTRAINT'+ #Constraint
EXEC (#REL_tbl)
------------------------------------------------------------
DECLARE #Update_tbl VARCHAR(max) = N'UPDATE '+ #Tableee + 'SET ' + #Columnee + '=' + #NewValueInt+ ' WHERE' + #Columnee + '=' + #SearchStrColumnValue
EXEC (#Update_tbl)
DECLARE #Sealing_tbl VARCHAR(max) = N'ALTER TABLE' + #Tableee + 'ADD CONSTRAINT' + #Constraint + 'PRIMARY KEY CLUSTERED (SELECT * FROM #PK_tbl)'
EXEC (#Update_tbl)
END
I wrote the following stored procedure for querying the database. Can someone tell me if this dynamic query stored procedure is vulnerable to a SQL injection attack?
If it is, how to modify the following code to prevent SQL injection attacks?
The second question is OPTION (RECOMPILE) at the end of the WHERE cause, is it necessary with every execution?
CREATE PROCEDURE DataMapMainQuery
(#DataMapID VARCHAR(MAX),
#DataMapIDName VARCHAR(MAX),
#StartIndex INT,
#MaximumRows INT,
#sortExpression VARCHAR(MAX))
AS
BEGIN
DECLARE #FilteredTotalRows AS INT
DECLARE #SqlString NVARCHAR(MAX)
DECLARE #WhereString1 NVARCHAR(MAX)
DECLARE #WhereString2 NVARCHAR(MAX)
IF (#DataMapID IS NULL)
SET #WhereString1 = ' AND (DataMapID LIKE ' + '''%%''' + ' OR NULL IS NULL)'
ELSE
SET #WhereString1 = ' AND (DataMapID LIKE ' + '''%' + #DataMapID + '%''' + ' OR ''' + #DataMapID + ''' IS NULL)'
IF (#DataMapIDName IS NULL)
SET #WhereString2 = ' AND (DataMapIDName LIKE ' + '''%%''' + ' OR NULL IS NULL)'
ELSE
SET #WhereString2 = ' AND (DataMapIDName LIKE ' + '''%' + #DataMapIDName + '%''' + ' OR ''' + #DataMapIDName + ''' IS NULL)'
IF (#sortExpression IS NULL)
SET #sortExpression = 'DataMapID'
SELECT
#FilteredTotalRows = COUNT(*)
FROM
DataMapMain
WHERE
1 = 1
AND (DataMapID LIKE '%' + #DataMapID + '%' OR #DataMapID IS NULL)
AND (DataMapIDName LIKE '%' + #DataMapIDName + '%' OR #DataMapIDName IS NULL)
IF (#FilteredTotalRows < #StartIndex + 1)
BEGIN
SET #SqlString = '
SELECT
DataMapID, DataMapIDName,
DataMapGroup, DataMapGroupRemark,
CONVERT(BIGINT, TimeStamp) AS TimeStamp
FROM
(SELECT
ROW_NUMBER() OVER (ORDER BY ' + #sortExpression + ') AS RowNumber,
DataMapID, DataMapIDName,
DataMapGroup, DataMapGroupRemark,
TimeStamp
FROM
DataMapMain
WHERE
1 = 1'
+ #WhereString1
+ #WhereString2
+ ') DataMapMain
WHERE
RowNumber >= 1
AND RowNumber < (1 + ' + CONVERT(NVARCHAR(10), #MaximumRows) + ')
OPTION (RECOMPILE)'
END
ELSE
BEGIN
SET #SqlString = '
SELECT
DataMapID
,DataMapIDName
,DataMapGroup
,DataMapGroupRemark
,CONVERT(bigint, TimeStamp) as TimeStamp
FROM
(
Select ROW_NUMBER() over (order by ' + #sortExpression + ') as RowNumber
,DataMapID
,DataMapIDName
,DataMapGroup
,DataMapGroupRemark
,TimeStamp
From DataMapMain
WHERE
1 = 1'
+ #WhereString1
+ #WhereString2
+ ') DataMapMain
WHERE
RowNumber >= (' + CONVERT(nvarchar(10),#StartIndex) + ' + 1) and RowNumber < (' + CONVERT(nvarchar(10),#StartIndex) + ' + 1 + ' + CONVERT(nvarchar(10),#MaximumRows) + ' )
OPTION (RECOMPILE)'
END
PRINT #SqlString
PRINT #FilteredTotalRows
EXEC sp_executesql #SqlString
END
Just use sp_executesql with parameters. Build your dynamic T-SQL statements, but instead the value add #parameter_name. Then call the routine like this:
EXEC sp_executesql #sql
,N'#parameter_name1 INT, #parameter_name2 VARCHAR(128), #parameter_name3 BIT'
,#parameter_name1, #parameter_name2, #parameter_name3;
So far your #DataMapID and #DataMapName are safe because your building it first before applying in your main sql query. I would suggest adding these lines to check proper values of your sort expression, maxrows and start index
IF (#sortExpression NOT IN ('ASC', 'DESC'))
BEGIN
RAISERROR('invalid order expression', 16,1);
RETURN;
END;
IF (TRY_CAST(#StartIndex as int) = null or TRY_CAST(#MaximumRows as int) = null)
BEGIN
RAISERROR('invalid startindex or maximum rows', 16,1);
RETURN;
END;
Adding OPTION(RECOMPILE) hint provides to rebuild a new execution plan for the query execution for every execution. Under some circumstances it can help to improve the performance. However the recompile operation uses memory and CPU resources in order to generate new execution plan. As a result, if you are not sure about the effects of the performance you don't use it
Thanks for all of your helps, I rewrote the code below. Please let me know if it is not OK. thank you all!
CREATE PROCEDURE DataMapMainQuery
(#DataMapID VARCHAR(MAX),
#DataMapIDName VARCHAR(MAX),
#StartIndex INT,
#MaximumRows INT,
#sortExpression VARCHAR(MAX))
AS
BEGIN
DECLARE #FilteredTotalRows AS INT
DECLARE #SqlString NVARCHAR(MAX)
DECLARE #params NVARCHAR(MAX);
DECLARE #WhereString1 NVARCHAR(MAX)
DECLARE #WhereString2 NVARCHAR(MAX)
IF (#DataMapID IS NULL)
SET #WhereString1 = ' AND (DataMapID LIKE ' + '''%%''' + ' OR NULL IS NULL)'
ELSE
SET #WhereString1 = ' AND (DataMapID LIKE ' + '''%' + #DataMapID + '%''' + ' OR ''' + #DataMapID + ''' IS NULL)'
IF (#DataMapIDName IS NULL)
SET #WhereString2 = ' AND (DataMapIDName LIKE ' + '''%%''' + ' OR NULL IS NULL)'
ELSE
SET #WhereString2 = ' AND (DataMapIDName LIKE ' + '''%' + #DataMapIDName + '%''' + ' OR ''' + #DataMapIDName + ''' IS NULL)'
IF (#sortExpression IS NULL)
SET #sortExpression = 'DataMapID'
SELECT
#FilteredTotalRows = COUNT(*)
FROM
DataMapMain
WHERE
1 = 1
AND (DataMapID LIKE '%' + #DataMapID + '%' OR #DataMapID IS NULL)
AND (DataMapIDName LIKE '%' + #DataMapIDName + '%' OR #DataMapIDName IS NULL)
IF (#FilteredTotalRows < #StartIndex + 1)
BEGIN
SET #SqlString = '
SELECT
DataMapID, DataMapIDName,
DataMapGroup, DataMapGroupRemark,
CONVERT(BIGINT, TimeStamp) AS TimeStamp
FROM
(SELECT
ROW_NUMBER() OVER (ORDER BY ' + #sortExpression + ') AS RowNumber,
DataMapID, DataMapIDName,
DataMapGroup, DataMapGroupRemark,
TimeStamp
FROM
DataMapMain
WHERE
1 = 1'
+ #WhereString1
+ #WhereString2
+ ') DataMapMain
WHERE
RowNumber >= 1
AND RowNumber < (1 + ' + CONVERT(NVARCHAR(10), #MaximumRows) + ')'
END
ELSE
BEGIN
SET #SqlString = '
SELECT
DataMapID
,DataMapIDName
,DataMapGroup
,DataMapGroupRemark
,CONVERT(bigint, TimeStamp) as TimeStamp
FROM
(
Select ROW_NUMBER() over (order by ' + #sortExpression + ') as RowNumber
,DataMapID
,DataMapIDName
,DataMapGroup
,DataMapGroupRemark
,TimeStamp
From DataMapMain
WHERE
1 = 1'
+ #WhereString1
+ #WhereString2
+ ') DataMapMain
WHERE
RowNumber >= (' + CONVERT(nvarchar(10),#StartIndex) + ' + 1) and RowNumber < (' + CONVERT(nvarchar(10),#StartIndex) + ' + 1 + ' + CONVERT(nvarchar(10),#MaximumRows) + ' )'
END
SET #params = '
#DataMapID VARCHAR(MAX)
,#DataMapIDName VARCHAR(MAX)
,#StartIndex INT
,#MaximumRows INT
,#sortExpression VARCHAR(MAX)';
EXEC sp_executesql
#SqlString
,#params
,#DataMapID
,#DataMapIDName
,#StartIndex
,#MaximumRows
,#sortExpression;
END
I'm currently new to sql server.
I am using stored procedure with the help of visual studio 2010 express.
And i am experimenting on stored procedure in sql server when i found this error, which is very annoying :
Incorrect syntax near keyword 'IF
UPDATE [table_name]
SET
[delete_datetime] = CURRENT_TIMESTAMP,
[delete_user_record_id] = 2
WHERE [table_name].[record_id] = 2
Here's my stored procedure function. It is to update time stamps on my current table :
USE [MGroupIS]
GO
/****** Object: StoredProcedure [dbo].[iSP_SET_DATA_INFORMATION] Script Date: 02/01/2016 14:40:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SP_SET_DATA_INFORMATION]
--Paramateres
AS
DECLARE #sql AS NVARCHAR(4000)
DECLARE #pFlag AS VARCHAR(6)
SET #pFlag = #flag
--IF Delete
IF #pFlag = 'DELETE'
BEGIN
SET #sql = 'UPDATE [' + #tableName + '] ' + CHAR(13) +
' SET ' + CHAR(13) +
' [delete_datetime] = CURRENT_TIMESTAMP, ' + CHAR(13) +
' [delete_user_record_id] = ' + CAST(#userRecordID AS VARCHAR(20)) + CHAR(13) +
' WHERE [' + #tableName + '].[' + #keyField + '] = ' + CAST(#recordID AS VARCHAR(20))
END
ELSE
BEGIN
SET #sql = 'UPDATE [' + #tableName + '] ' + CHAR(13) +
' SET ' + CHAR(13) +
' [edit_datetime] = CURRENT_TIMESTAMP, ' + CHAR(13) +
' [edit_user_record_id] = ' + CAST(#userRecordID AS CHAR(3))
END
EXEC sp_executeSQL #sql
PRINT #sql
And i call the stored procedure from another stored procedure (ISP_CFG_ACCESS_RIGHT_QUERY) :
ELSE IF #action = 'SAVE'
--SAVE Action
BEGIN
--If saved
IF #removeUnsaved = 0
BEGIN
UPDATE [CFG_ACCESS_RIGHT]
SET [CFG_ACCESS_RIGHT].[NAME] = '' + #name + '',
[CFG_ACCESS_RIGHT].[NOTE] = '' + #note + ''
WHERE [CFG_ACCESS_RIGHT].[RECORD_ID] = #recordID
DELETE FROM [CFG_ACCESS_RIGHT_DETAIL]
WHERE [CFG_ACCESS_RIGHT_DETAIL].[access_right_record_id] = #recordID
SET #sql = 'INSERT INTO [CFG_ACCESS_RIGHT_DETAIL] ' + CHAR(13) +
'SELECT * FROM [' + #tempTable + '] ' + CHAR(13) +
' WHERE [' + #tempTable + '].[delete_datetime] IS NULL;'
EXEC sp_executeSQL #sql
EXEC [ISP_SET_DATA_INFORMATION]
'CFG_ACCESS_RIGHT',
'record_id',
#userRecordID,
#recordID,
#voidStatus,
#voidReason,
#flag,
0
EXEC [ISP_SET_DATA_INFORMATION]
'CFG_ACCESS_RIGHT_DETAIL',
'access_right_record_id',
#userRecordID,
#recordID,
#voidStatus,
#voidReason,
#flag,
0
END
--If leave without saving
ELSE
BEGIN
EXEC [ISP_SET_DATA_INFORMATION]
'CFG_ACCESS_RIGHT',
'record_id',
#userRecordID,
#recordID,
#voidStatus,
#voidReason,
'DELETE',
0
END
Please help.
Thank you before hand.
Edit 1 : Isolating the potential problematic part. Please help
Your dynamic DROP table statement in procedure is syntactically wrong.
It should be like this,
IF OBJECT_ID('tablename', 'U') IS NOT NULL
DROP TABLE tablename;
In addition to that there are few syntax errors in your T-SQL too. I have fixed it.
Please refer this code,
IF #pFlag = 'DELETE'
BEGIN
SET #sql = 'UPDATE [' + #tableName + '] ' + Char(13)
+ ' SET ' + Char(13)
+ ' [delete_datetime] = CURRENT_TIMESTAMP, '
+ Char(13) + ' [delete_user_record_id] = '
+ Cast(#userRecordID AS VARCHAR(20))
+ Char(13) + ' WHERE [' + #tableName + '].['
+ #keyField + '] = '
+ Cast(#recordID AS VARCHAR(20))
END
ELSE
BEGIN
SET #sql = 'UPDATE [' + #tableName + '] ' + Char(13)
+ ' SET ' + Char(13)
+ ' [edit_datetime] = CURRENT_TIMESTAMP, '
+ Char(13) + ' [edit_user_record_id] = '
+ Cast(#userRecordID AS CHAR(3))
--IF New Record
IF #flag = 'NEW'
BEGIN
SET #sql = #sql + ', ' + Char(13)
+ '[create_datetime] = CURRENT_TIMESTAMP, '
+ Char(13) + '[create_user_record_id] = '
+ Cast(#userRecordID AS CHAR(3))
END
--IF Void Record
IF #voidStatus = 1
BEGIN
SET #sql = #sql + ', ' + Char(13) + '[void_status] = 1, '
+ Char(13)
+ '[void_datetime] = CURRENT_TIMESTAMP, '
+ Char(13) + '[void_user_record_id] = '
+ Cast(#userRecordID AS CHAR(3)) + ', '
+ Char(13) + '[void_reason] = ''' + #voidReason
+ ''''
END
ELSE
BEGIN
SET #sql = #sql + ', ' + Char(13) + '[void_status] = 0, '
+ Char(13) + '[void_datetime] = NULL, '
+ Char(13) + '[void_user_record_id] = '
+ Cast(#userRecordID AS CHAR(3)) + ', '
+ Char(13) + '[void_reason] = NULL'
END
--IF Print
IF #printed = 1
BEGIN
SET #sql = #sql + ', ' + Char(13)
+ '[print_count] = [print_count] + 1, '
+ Char(13) + '[last_print_datetime] = NULL, '
+ Char(13) + '[print_user_record_id] = 0'
+ Cast(#userRecordID AS CHAR(3))
END
SET #sql = #sql + ', ' + Char(13)
+ 'record_version = record_version + 1 '
+ Char(13) + ' WHERE [' + #tableName + '].['
+ #keyField + '] = '
+ Cast(#recordID AS VARCHAR(20))
END
EXEC Sp_executesql
#sql
PRINT #sql
Procedure Code:
ALTER PROCEDURE [dbo].[Sp_cfg_access_right_query] #recordID INT,
#userRecordID INT,
#action CHAR(4),
#flag CHAR(6),
#tempTable VARCHAR(50),
#name VARCHAR(50),
#note VARCHAR(1000),
#voidStatus BIT,
#voidReason VARCHAR(200),
#removeUnsaved BIT
AS
--Setting NULL values
SET #recordID = Isnull(#recordID, 0)
SET #userRecordID = Isnull(#recordID, 0)
SET #action = Isnull(#action, '')
SET #flag = Isnull(#flag, '')
SET #tempTable = Isnull(#tempTable, '')
SET #name = Isnull(#name, '')
SET #note = Isnull(#note, '')
SET #voidStatus = Isnull(#voidStatus, 0)
SET #voidReason = Isnull(#voidReason, '')
DECLARE #detailCount INT
DECLARE #currentID INT
DECLARE #sql NVARCHAR(1000)
DECLARE #temp VARCHAR(100)
DECLARE #tempConstraint VARCHAR(100)
IF #action = 'LOAD'
--LOAD action
BEGIN
SET #temp = 'CFG_TEMP_ARD_'
+ Replace(Cast(Newid() AS VARCHAR(50)), '-', '')
SET #tempConstraint = Cast(Year(CURRENT_TIMESTAMP) AS VARCHAR(4))
+ Cast(Month(CURRENT_TIMESTAMP) AS VARCHAR(2))
+ Cast(Day(CURRENT_TIMESTAMP) AS VARCHAR(2))
+ Cast(Datepart(HOUR, CURRENT_TIMESTAMP) AS VARCHAR(2))
+ Cast(Datepart(MINUTE, CURRENT_TIMESTAMP) AS VARCHAR(2))
+ Cast(Datepart(SECOND, CURRENT_TIMESTAMP) AS VARCHAR(2))
+ Cast(Datepart(MILLISECOND, CURRENT_TIMESTAMP) AS VARCHAR(3))
SET #sql = 'SELECT * INTO [' + #temp
+ '] FROM [CFG_ACCESS_RIGHT_DETAIL] WHERE 1=0;'
EXEC Sp_executesql
#sql
SET #sql = 'ALTER TABLE [' + #temp + '] ' + Char(13)
+ 'ADD CONSTRAINT PK_' + #tempConstraint
+ Char(13)
+ 'PRIMARY KEY ([record_id], [access_right_record_id]);'
EXEC Sp_executesql
#sql
IF #flag = 'NEW'
BEGIN
INSERT INTO [CFG_ACCESS_RIGHT]
(NAME,
note,
record_version)
VALUES ('',
'',
1)
SELECT #recordID = Scope_identity()
FROM [CFG_ACCESS_RIGHT];
END
SELECT #recordID currentID,
#temp tempTable
--Load Access Right
SELECT *
FROM [CFG_ACCESS_RIGHT]
WHERE [record_id] = #recordID
--Check & Return Detail Count
SELECT #detailCount = ##ROWCOUNT
FROM [CFG_ACCESS_RIGHT_DETAIL]
WHERE [access_right_record_id] = #recordID
SELECT Isnull(#detailCount, 0) detailCount
--Load Access Right Details if exist
IF #detailCount > 0
BEGIN
SELECT *
FROM [CFG_ACCESS_RIGHT_DETAIL]
WHERE [access_right_record_id] = #recordID
AND [delete_datetime] IS NULL
END
END
ELSE IF #action = 'SAVE'
--SAVE Action
BEGIN
--If saved
IF #removeUnsaved = 0
BEGIN
UPDATE [CFG_ACCESS_RIGHT]
SET [CFG_ACCESS_RIGHT].[NAME] = '' + #name + '',
[CFG_ACCESS_RIGHT].[NOTE] = '' + #note + ''
WHERE [CFG_ACCESS_RIGHT].[RECORD_ID] = #recordID
DELETE FROM [CFG_ACCESS_RIGHT_DETAIL]
WHERE [CFG_ACCESS_RIGHT_DETAIL].[access_right_record_id] = #recordID
SET #sql = 'INSERT INTO [CFG_ACCESS_RIGHT_DETAIL] '
+ Char(13) + 'SELECT * FROM [' + #tempTable + '] '
+ Char(13) + ' WHERE [' + #tempTable
+ '].[delete_datetime] IS NULL;'
EXEC Sp_executesql
#sql
EXEC [Sp_set_data_information]
'CFG_ACCESS_RIGHT',
'record_id',
#userRecordID,
#recordID,
#voidStatus,
#voidReason,
#flag,
0
EXEC [Sp_set_data_information]
'CFG_ACCESS_RIGHT_DETAIL',
'access_right_record_id',
#userRecordID,
#recordID,
#voidStatus,
#voidReason,
#flag,
0
END
--If leave without saving
ELSE
BEGIN
EXEC [Sp_set_data_information]
'CFG_ACCESS_RIGHT',
'record_id',
#userRecordID,
#recordID,
#voidStatus,
#voidReason,
'DELETE',
0
END
END
SET #sql ='IF OBJECT_ID(''' + #tempTable
+ ''', ''U'') IS NOT NULL
DROP TABLE ' + #tempTable
EXEC Sp_executesql
#sql
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.