且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在动态sql语句中使用表变量?

更新时间:2023-01-19 17:11:42

您的EXEC在不同的上下文中执行,因此它不知道在原始上下文中已声明的任何变量.您应该能够使用临时表而不是表变量,如下面的简单演示所示.

Your EXEC executes in a different context, therefore it is not aware of any variables that have been declared in your original context. You should be able to use a temp table instead of a table variable as shown in the simple demo below.

create table #t (id int)

declare @value nchar(1)
set @value = N'1'

declare @sql nvarchar(max)
set @sql = N'insert into #t (id) values (' + @value + N')'

exec (@sql)

select * from #t

drop table #t