Using a variable in Dynamic Query in SQL Server
-
12-12-2019 - |
Question
What I'm trying to do from this query is i'm trying to get all the rows which are older than the specified Cutoffnumber from customertransaction table:
@Cutoffnumber INT
SELECT @SQL = 'SELECT * FROM customertransaction WHERE DATEDIFF(DD, Transactiondate, GETDATE()) > @Cutoffnumber '
But i'm getting the below error, Note that this is a dynamic SQL query.
Must declare the scalar variable "@Cutoffnumber"
How should I go about.
Solution
Look into sp_executesql
OTHER TIPS
Decalre @Cutoffnumber INT
Set @Cutoffnumber = @someValue
SELECT @SQL = 'SELECT * FROM customertransaction WHERE DATEDIFF(DD, Transactiondate, GETDATE()) >' + @Cutoffnumber
Though it seems like you could do this without dynamic SQL:
Declare @Cutoffnumber INT
Set @Cutoffnumber = @someValue
SELECT * FROM customertransaction WHERE DATEDIFF(DD, Transactiondate, GETDATE()) > @Cutoffnumber
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow