执行带嵌入参数的sql——sp_executesql

来源:互联网 发布:剑灵读图慢怎么优化 编辑:程序博客网 时间:2024/06/05 14:27
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
通常执行sql语句,大家用的都是exec,exec功能强大,但不支持嵌入参数,sp_executesql解决了这个问题。抄一段sqlserver帮助:

sp_executesql
执行可以多次重用或动态生成的Transact-sql语句或批处理。Transact-sql语句或批处理可以包含嵌入参数。
语法
sp_executesql[@stmt=]stmt
[
&nbsp;&nbsp;&nbsp;&nbsp;{,[@params=]N'@parameter_name&nbsp;data_type[,...n]'}
&nbsp;&nbsp;&nbsp;&nbsp;{,[@param1=]'value1'[,...n]}
]
参数
[@stmt=]stmt

包含Transact-sql语句或批处理的Unicode字符串,stmt必须是可以隐式转换为ntext的Unicode常量或变量。不允许使用更复杂的Unicode表达式(例如使用+运算符串联两个字符串)。不允许使用字符常量。如果指定常量,则必须使用N作为前缀。例如,Unicode常量N'sp_who'是有效的,但是字符常量'sp_who'则无效。字符串的大小仅受可用服务器内存限制。

stmt可以包含与变量名形式相同的参数,例如:

N'SELECT*FROMEmployeesWHEREEmployeeID=@IDParameter'

stmt中包含的每个参数在@params参数定义列表和参数值列表中均必须有对应项。

[@params=]N'@parameter_name&nbsp;data_type[,...n]'

字符串,其中包含已嵌入到stmt中的所有参数的定义。该字符串必须是可以隐式转换为ntext的Unicode常量或变量。每个参数定义均由参数名和数据类型组成。n是表明附加参数定义的占位符。stmt中指定的每个参数都必须在@params中定义。如果stmt中的Transact-sql语句或批处理不包含参数,则不需要@params。该参数的默认值为NULL。

[@param1=]'value1'

参数字符串中定义的第一个参数的值。该值可以是常量或变量。必须为stmt中包含的每个参数提供参数值。如果stmt中包含的Transact-sql语句或批处理没有参数,则不需要值。

n

附加参数的值的占位符。这些值只能是常量或变量,而不能是更复杂的表达式,例如函数或使用运算符生成的表达式。
返回代码值
0(成功)或1(失败)
结果集
从生成sql字符串的所有sql语句返回结果集。


例子(感谢邹建提供)


declare@uservarchar(1000)
declare@moTablevarchar(20)
select@moTable='MT_10'




declare@sqlnvarchar(4000)&nbsp;--定义变量,注意类型



set@sql='select@user=count(distinctuserid)&nbsp;from'+@moTable&nbsp;--为变量赋值

--执行@sql中的语句
execsp_executesql@sql
&nbsp;,N'@uservarchar(1000)out'&nbsp;--表示@sql中的语句包含了一个输出参数
&nbsp;,@userout&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;--和调用存储过程差不多,指定输出参数值

print@user



&nbsp;


&nbsp;本例中,@moTable为嵌入参数。
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击