获取动态SQL查询语句返回值(sp_executesql)

在写存储过程时经常会遇到需要拼接SQL语句的情况,一般情况下仅仅是为了执行拼接后的语句使用exec(@sql)即可。

而今天的一个存储过程却需要获取动态SQL的查询结果。

需求描述:在某表中根据Id值查询Cost值(表名不确定但表结构确定,如下面的Product表)

如果不考虑获取返回值,我们这样写即可:

  declare @tableName varchar(50)
  declare @id varchar(10)
  declare @cost numeric(18,2)
  declare @sql nvarchar(200)
  
  set @tableName='Product'
  set @id='1'
  set @sql='select Cost from '+@tableName+' where Id='+@id
  exec(@sql)

要获取返回值首先尝试的是下面两个方法:

set @sql='select @cost=Cost from '+@tableName+' where Id='+@id  --错误方法1
set @cost=(exec(@sql))    --错误方法2

以上两种方法均会报错,求助万能的网络发现一个可爱的函数--sp_executesql可以满足我们的要求:

  set @sql='select @cost=Cost from '+@tableName+' where Id=@id'
  exec sp_executesql @sql, N'@cost numeric(18,2) out,@id varchar(10)', @cost out,@id

不仅能获取返回值,还能传参有没有!只可惜表名依然需要拼接在SQL语句中。

注意:@sql的类型需要是'ntext/nchar/nvarchar'这三种之一。

园友万德源sp_executesql介绍和使用帖中有关于此函数更详细的介绍。

原文地址:https://www.cnblogs.com/walden1024/p/4079777.html