存储过程中执行SQL并返回值

在存储过程中经常需要执行程序组成的SQL语句,可以使用exec(@sql),
也可以使用exec sp_executesql @sql。但使用sp_executesql要优于exec,建议使用 sp_executesql 而不要使用 EXECUTE 语句执行字符串。支持参数替换不仅使 sp_executesql 比 EXECUTE 更通用,而且 还使 sp_executesql 更有效,因为它生成的执行计划更有可能被 SQL Server 重新使用。

但如果使用sp_executesql ,全局变量比如@@rowcount将没有正确值,而exec有,如果想返回该SQL中某一字段的值可使用他的参数,例如:
@sql='select @id=id from table'
exec sp_executesql @sql N'@id int out ',@id out
print @id

posted @ 2007-05-21 13:13  Yoshow  阅读(1296)  评论(0编辑  收藏  举报