I have a dynamic query where in I want to add the value of a local variable to every row of the result set. I have a simplified version of the example below.
While this query works fine:
DECLARE @purchaseDate AS DATE
SET @purchaseDate = '12/23/2020'
SELECT Name, @purchaseDate
FROM Fruits
The similar one in dynamic SQL does not work:
DECLARE @query AS NVARCHAR(MAX),
@purchaseDate AS DATE
SET @purchaseDate = '12/23/2020'
SET @query = 'SELECT Name, @purchaseDate FROM Fruits'
EXEC sp_executesql @query
I get the error
Must declare the scalar variable "@purchaseDate".
So I assumed I might need to declare my purchaseDate inside the query as the dynamic SQL query cannot access the variable. So I tried this:
DECLARE @query AS NVARCHAR(MAX)
SET @query = 'DECLARE @purchaseDate AS DATE' +
'SET @purchaseDate = ' + '12/23/2020 ' +
'SELECT Name, @purchaseDate FROM Fruits'
EXEC sp_executesql @query
But I get the same error message.
How do I go about fixing it?