How do I pass a list as a parameter in a stored procedure?

前端 未结 7 1523
暖寄归人
暖寄归人 2020-12-02 22:15

Looking to pass a list of User IDs to return a list names. I have a plan to handle the outputed names (with a COALESCE something or other) but trying to find the best way to

7条回答
  •  暖寄归人
    2020-12-02 22:51

    I solved this problem through the following:

    1. In C # I built a String variable.

    string userId="";

    1. I put my list's item in this variable. I separated the ','.

    for example: in C#

    userId= "5,44,72,81,126";
    

    and Send to SQL-Server

     SqlParameter param = cmd.Parameters.AddWithValue("@user_id_list",userId);
    
    1. I Create Separated Function in SQL-server For Convert my Received List (that it's type is NVARCHAR(Max)) to Table.
    CREATE FUNCTION dbo.SplitInts  
    (  
       @List      VARCHAR(MAX),  
       @Delimiter VARCHAR(255)  
    )  
    RETURNS TABLE  
    AS  
      RETURN ( SELECT Item = CONVERT(INT, Item) FROM  
          ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)')  
            FROM ( SELECT [XML] = CONVERT(XML, ''  
            + REPLACE(@List, @Delimiter, '') + '').query('.')  
              ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y  
          WHERE Item IS NOT NULL  
      );
    
    1. In the main Store Procedure, using the command below, I use the entry list.

    SELECT user_id = Item FROM dbo.SplitInts(@user_id_list, ',');

提交回复
热议问题