通常我们使用如下语句进行返回参数值:
程序代码
declare @id int
Select top 1 @id=id from union_user
Select top 1 @id=id from union_user
但是使用下边的语句是不是也可以呢?
程序代码
declare @id int,@sql nvarchar(200)
set @sql = 'Select top 1 @id=id from union_user'
exec(@sql)
set @sql = 'Select top 1 @id=id from union_user'
exec(@sql)
经检测这样写是不行的,提示:必须声明变量 '@id'。最终借助sp_executesql存储过程才实现:
程序代码
declare @id int,@strSql nvarchar(200)
set @strSql = N' Select top 1 @id=id from union_user'
exec sp_executesql @strSql,N'@id int output',@id output
set @strSql = N' Select top 1 @id=id from union_user'
exec sp_executesql @strSql,N'@id int output',@id output
程序代码
declare @id int,@strSql nvarchar(200)
set @strSql = N' Select top 1 id from union_user'
exec @id = sp_executesql @strSql
set @strSql = N' Select top 1 id from union_user'
exec @id = sp_executesql @strSql
需要注意的是sp_executesql第一个参数@strSql必须是"ntext/nchar/nvarchar"类型,否则会出错提示:过程需要参数 '@statement' 为 'ntext/nchar/nvarchar' 类型。
还有一点值得注意的是@strSql的长度最好设置大一点,开始时我设置为50,发现老是得不到正确的结果,print @strSql才知道被截断了!