sql 在字符串里面定义变量 外面怎么获取

SET @str ='
declare @temp table
(
[ID] INT IDENTITY(1,1)
)
'
exec(@str)
select * from @temp

@temp 怎么获取

想在动态执行SQL时获得其执行过程中的变量值,那么要使用sp_executesql这个存储过程。它支持输入变量和输出变量,但是变量必须为标量类型,不支持表变量。所以,你要获得动态SQL中的表变量是实现不了的。

如果是要获得动态SQL中执行的结果集的话,则可以使用临时表来保存数据。

 

获取动态SQL中变量的示例:

declare @str nvarchar(200)
set @str = 'set @b = 100'
declare @val int
execute sp_executesql @str, N'@b int output', @val out
select @val

温馨提示:答案为网友推荐,仅供参考
相似回答