动态SQL查询变量声明出错

时间:2014-01-09 20:40:32

标签: sql sql-server variables

我在SQL

中运行了以下查询
declare @h nvarchar(max)
declare @i int
set @i =1
declare @two nvarchar(max)
select @h = 'set @two = (select word from #LocalTempTable where Idcolumn =' + cast(@i as nvarchar(max)) +')'
exec(@h)
print @two

我收到以下错误

Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "@two".

为什么会这样?

2 个答案:

答案 0 :(得分:2)

您的变量范围存在问题,@ h变量中的@two未声明。

您可以在@h变量中声明它:

DECLARE @h nvarchar(max)
       ,@i INT = 1
SELECT @h = 'declare @two nvarchar(max) set @two = (select ''dog' + CAST(@i as nvarchar(max)) +''')'
EXEC(@h)

你的#temp表仍然存在范围问题,并在内部声明它使其在外部不可用,因此没有太多指向它。

答案 1 :(得分:2)

以下是更正后的内容。这是sqlfiddle

declare @h nvarchar(max)
declare @i int
set @i =1
declare @two nvarchar(max)
select @h = 'select @to = word from #LocalTempTable where Idcolumn =' + cast(@i as nvarchar(max))
exec sp_executesql @h, N'@to nvarchar(max) output', @to=@two output
print @two
相关问题