解决存储过程中SQL字符串语句执行引入参数的问题

2014-11-24 15:34:17 · 作者: · 浏览: 0
解决存储过程中SQL字符串语句执行引入参数的问题
最近在写存储过程的时候,发现一个问题,是关于存储过程中字符串SQL中引入参数的问题。
且看下例:
[sql]
declare @count int
select @count=count(*) from student where Name in ('Chamy','Jundy')
print @count
如果我们要在上面句子中In后面引入参数:
那必须这么写:
[sql]
declare @count int
declare @Names nvarchar(200)
set @Names='''Chamy'',''Jundy'''
declare @sql nvarchar(500)
set @sql='select @count=count(*) from student where Name in ('+@Names+')'
exec(@sql)
print @count
这里我们选择打印了@count参数,但是发现SQL执行会报错,显示@count参数没有定义。想过才发现,由于我们exec的只是@sql里的SQL语句,确实是没有定义@count参数的。而作为一个公用的参数,如果我想在@sql语句执行完后依然得到@count参数,那应该如何处理?
经过查找各种资料以及询问资深的SQL开发人员,得到以下方式来解决如上问题:
[sql]
declare @count int
declare @Names nvarchar(200)
set @Names='''Chamy'',''Jundy'''
declare @sql nvarchar(500)
set @sql='select @count=count(*) from student where Name in ('+@Names+')'
EXEC sp_executesql @sql,N'@count int OUTPUT',@count OUTPUT
print @count
我们注意到,能过在sp_executesql这个存储过程中执行@sql参数,并重新定义@count参数,并使用@sql之外的参数@count进行输出,就能很好的处理参数传入的问题。