在寫存儲過程時經常會遇到需要拼接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介紹和使用帖中有關於此函數更詳細的介紹。