如何将可变数量的参数传递给SQL Server存储过程? [英] How to pass a variable number of parameters to a SQL Server stored procedure?
本文介绍了如何将可变数量的参数传递给SQL Server存储过程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在小型Web应用程序中使用了SQL Server 2005.我想要将参数传递给SP. 但是有一个条件.可以不时更改的参数数量. 想想,这一次我传递名称和地址,下次我传递名称,姓氏,地址,
I used SQL Server 2005 for my small web application. I Want pass parameters to SP . But there is one condition. number of parameter that can be change time to time. Think ,this time i pass name and Address , next time i pass name,surname,address ,
此参数范围可能是1-30,
this parameter range may be 1-30 ,
推荐答案
您使用默认参数声明该过程,然后使用命名参数而不是位置参数调用该过程:
You declare the procedure with default parameters and you invoke it with named parameters instead of positional parameters:
CREATE PROCEDURE usp_myProcedure
@name varchar(100) = '',
@surname varchar(100) = '',
@address varchar(100) = ''
AS
BEGIN
...
END
从T-SQL调用它:
exec usp_myProcedure @name='John', @surname = 'Doe';
exec usp_myProcedure @name='Jane', @address = '123 Anystreet';
要从C#调用它:
SqlCommand cmd = new SqlCommand('usp_MyProcedure', ...);
cmd.CommandType = commandtype.StoredProcedure;
cmd.Parameters.AddWithValue('@name', 'John');
cmd.Parameters.AddWithValue('@surname', 'Doe');
这篇关于如何将可变数量的参数传递给SQL Server存储过程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文