How to pass a variable number of parameters to a SQL Server stored procedure?

前端 未结 4 1142
执笔经年
执笔经年 2021-02-05 16:32

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

4条回答
  •  你的背包
    2021-02-05 16:43

    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
    

    to invoke it from T-SQL:

    exec usp_myProcedure @name='John', @surname = 'Doe';
    exec usp_myProcedure @name='Jane', @address = '123 Anystreet';
    

    To invoke it from C#:

    SqlCommand cmd = new SqlCommand('usp_MyProcedure', ...);
    cmd.CommandType = commandtype.StoredProcedure;
    cmd.Parameters.AddWithValue('@name', 'John');
    cmd.Parameters.AddWithValue('@surname', 'Doe');
    

提交回复
热议问题