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

时间:2019-03-04 16:58:06

标签: sql-server dynamicquery

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

此查询可以正常运行:

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

我收到错误

  

必须声明标量变量“ @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

但是我收到相同的错误消息。

我该如何解决?

2 个答案:

答案 0 :(得分:6)

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

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;

答案 1 :(得分:1)

使用预备语句在动态查询中放置变量的推荐方法:

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