两种动态SQL
參考:
http://www.cnblogs.com/wanyuan8/archive/2011/11/09/2243483.html
http://www.cnblogs.com/xbf321/archive/2008/11/02/1325067.html
?
兩種動態(tài)SQL
1. EXEC (@sql)
2. EXEC sp_executesql
性能:
sp_executesql提供了輸入輸出接口,更具有優(yōu)勢
sp_executesql根據(jù)參數(shù)重用執(zhí)行計(jì)劃,不需要每一次都重新編譯,提高了執(zhí)行性能; EXEC因?yàn)槊看螛?gòu)建的@sql字符串不一樣,必須重新編譯
除非您有令人信服的理由使用EXEC,否側(cè)盡量使用sp_executesql
注意:(執(zhí)行動態(tài)sql時候,防止sql注入攻擊)
1. 使用EXEC(@sql)時,如果您想訪問變量,必須把變量內(nèi)容串聯(lián)到動態(tài)構(gòu)建的代碼字符串中
?
2. sp_executesql后面跟有三部份,分別是 @stmt, @params, params_assignment
declare @sql nvarchar(200) declare @id varchar(20) declare @count int set @id='1' set @sql='select @count = count(1) from t_a where Rownum_id = @id' exec sp_executesql @sql, N'@count int out,@id varchar(20)',@count out,@id select @countsp_executesql使用:
sp_executesql要求動態(tài)Sql (即@stmt部分) 和動態(tài)Sql參數(shù)列表 (即@params部分) 必須是Nvarchar
N'@count int out,@id varchar(20)' 是@stmt內(nèi)的參數(shù)列表; @count out,@id 是為@params參數(shù)列表提供值的外部參數(shù)列表
sp_executesql 參數(shù)列表@params與外部提供值的參數(shù)列表params_assignment的順序必需一致; 如果不一致,必須顯式標(biāo)明,如 @id=@id, @count=@count out
動態(tài)SQl的參數(shù)列表與外部提供參數(shù)的參數(shù)列表參數(shù)名可以同名
轉(zhuǎn)載于:https://www.cnblogs.com/lynhou/p/6737830.html
總結(jié)
- 上一篇: 洛谷P1757 通天之分组背包 [201
- 下一篇: MYSQL AND OR的联用