我有存储过程,我必须传递参数,但问题是我不知道有多少参数会来,它可以是1,在下一个运行它可以是5.
cmd.Parameters.Add(new sqlParameter("@id",id)
任何人都可以帮助我如何在存储过程中传递这些可变数量的参数?
谢谢
解决方法
您可以以逗号分隔的列表传递它,然后使用拆分函数,并结合结果.
CREATE FUNCTION dbo.SplitInts ( @List VARCHAR(MAX),@Delimiter CHAR(1) ) RETURNS TABLE AS RETURN ( SELECT Item = CONVERT(INT,Item) FROM ( SELECT Item = x.i.value('(./text())[1]','INT') FROM ( SELECT [XML] = CONVERT(XML,'<i>' + REPLACE(@List,@Delimiter,'</i><i>') + '</i>').query('.') ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y WHERE Item IS NOT NULL );
现在你的存储过程:
CREATE PROCEDURE dbo.doStuff @List VARCHAR(MAX) AS BEGIN SET NOCOUNT ON; SELECT cols FROM dbo.table AS t INNER JOIN dbo.SplitInts(@List,',') AS list ON t.ID = list.Item; END GO
然后叫它:
EXEC dbo.doStuff @List = '1,2,3,...';
您可以在这里查看一些背景,其他选项和性能比较:
> http://sqlblog.com/blogs/aaron_bertrand/archive/2010/07/07/splitting-a-list-of-integers-another-roundup.aspx
> http://sqlperformance.com/2012/07/t-sql-queries/split-strings
> http://sqlperformance.com/2012/08/t-sql-queries/splitting-strings-follow-up
当然,如果您使用的是sql Server 2008或更高版本,则可以使用表值参数(TVP)更有效地传递这些数据.请看这里快速介绍:
> http://sqlperformance.com/2012/08/t-sql-queries/splitting-strings-now-with-less-t-sql