sp_executesql 使用

sp_executesql

---书写规则

---exec sp_executesql @sql,N'参数1 类型1,参数2 类型2,参数3 类型3 OUTPUT',参数1,参数2,参数3 OUTPUT;

---注意参数顺序必须对应好,习惯上把OUTPUT 参数放在最后

sp_executesql 比 之前的exec @sql 区别在可以实现参数的传入传出

declare @sql nvarchar(2000) 
declare @pid varchar(20) 
set @pid='001' 
set @sql='select count(1) from Sale (nolock) where pid=' + @pid 
exec @sql 

在传统的 exec 是无法将Count(*)传出到外面 的

但是如果用 sp_executesql 则很简单

declare @sql nvarchar(2000) 

declare @saleCount int 
declare @pid varchar(20) 
set @pid='001' 
set @sql='select @count=count(1) from Sale  (nolock) where pid=@pid' 
exec sp_executesql @sql, N'@count int out,@pid varchar(20)', @saleCount out ,@id 
print @saleCount 

set statistics time on
Go

declare @sql nvarchar(2000)

declare @recordCount int
declare @OpType int
set @OpType= 300305
set @sql='select @Count=count(1) from UserAmountLog (nolock) where OpType=@type'
exec sp_executesql @sql, N'@Count int out,@type int', @recordCount out ,@OpType
print @recordCount

用exec,由于每次传入的参数值不一样,所以每次生成的@sql就不一样,这样每执行一次Sql 就必须重新将要执行的动态Sql重新编译一次 
但是sp_executesql则不一样,由于将数值参数化,要执行的动态Sql永远不会变化,只是传入的参数的值在变化,那每次执行的时候就秒用重新编译,速度自然快多了 ! 

原文地址:https://www.cnblogs.com/zhshlimi/p/5591754.html