zoukankan      html  css  js  c++  java
  • 获取动态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介绍和使用帖中有关于此函数更详细的介绍。

  • 相关阅读:
    面试笔试
    scala(9) Monad
    scala (8) 模糊匹配
    scala (7) Set and Tuple
    scala (6) Map
    scala (5) 可变序列和不可变序列
    scala (4) 可变数组和不可变数组
    scala (3) Function 和 Method
    scala (2) while 和变量
    scala (1) for 循环
  • 原文地址:https://www.cnblogs.com/walden1024/p/4079777.html
Copyright © 2011-2022 走看看