将局部变量值添加到动态查询结果集中

To add a local variable value to a dynamic query result set

我有一个动态查询,我想将局部变量的值添加到结果集的每一行。我有以下示例的简化版本。

虽然此查询工作正常:

DECLARE @purchaseDate AS DATE
SET @purchaseDate = '12/23/2020'

SELECT Name, @purchaseDate 
FROM Fruits

动态中类似的SQL不起作用:

DECLARE @query AS NVARCHAR(MAX),
        @purchaseDate AS DATE

SET @purchaseDate = '12/23/2020'

SET @query = 'SELECT Name, @purchaseDate FROM Fruits' 

EXEC sp_executesql @query

我收到错误

Must declare the scalar variable "@purchaseDate".

所以我假设我可能需要在查询中声明我的 purchaseDate,因为动态 SQL 查询无法访问该变量。所以我尝试了这个:

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

但是我得到了同样的错误信息。

我该如何修复它?

使用准备好的语句将变量放入动态查询的推荐方法:

if OBJECT_ID('Fruits') is not null drop table Fruits

create table Fruits(
    name varchar(100)
)

insert into Fruits
values('apple')

DECLARE @purchaseDate AS DATE
SET @purchaseDate = '12/23/2020'

DECLARE @P1 int;  
EXEC sp_prepare @P1 output,   
    N'@purchaseDate date',  
    N'SELECT Name, @purchaseDate FROM Fruits';  
EXEC sp_execute @P1, @purchaseDate;  
EXEC sp_unprepare @P1;  

看看Microsoft Doku

如果你懒惰或者只是想要一个简单的临时解决方案(不推荐):

if OBJECT_ID('Fruits') is not null drop table Fruits

create table Fruits(
    name varchar(100)
)

insert into Fruits
values('apple')

DECLARE @query  AS NVARCHAR(MAX),
@purchaseDate AS DATE
SET @purchaseDate = '12/23/2020'
set @query = 'SELECT Name, ' + convert(nvarchar(10),@purchaseDate, 12) + ' FROM Fruits' 
exec sp_executesql @query

您不能在动态语句中引用在动态语句外部声明的变量。您需要在参数中添加声明并传递值:

DECLARE @query  AS nvarchar(MAX),
        @purchaseDate AS date;
SET @purchaseDate = '20201223';
SET @query = 'SELECT Name,@purchaseDate FROM Fruits;'; 
EXEC sp_executesql @query, N'@purchaseDate date', @purchaseDate = @purchaseDate;