How to pass an array into a SQL Server stored procedure

前端 未结 11 2414
轻奢々
轻奢々 2020-11-21 23:28

How to pass an array into a SQL Server stored procedure?

For example, I have a list of employees. I want to use this list as a table and join it with another table.

11条回答
  •  温柔的废话
    2020-11-21 23:59

    This will help you. :) Follow the next steps,

    1. Open the Query Designer
    2. Copy Paste the Following code as it is,it will create the Function which convert the String to Int

      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
        );
      GO
      
    3. Create the Following stored procedure

       CREATE PROCEDURE dbo.sp_DeleteMultipleId
       @List VARCHAR(MAX)
       AS
       BEGIN
            SET NOCOUNT ON;
            DELETE FROM TableName WHERE Id IN( SELECT Id = Item FROM dbo.SplitInts(@List, ',')); 
       END
       GO
      
    4. Execute this SP Using exec sp_DeleteId '1,2,3,12' this is a string of Id's which you want to delete,

    5. You convert your array to string in C# and pass it as a Stored Procedure parameter

      int[] intarray = { 1, 2, 3, 4, 5 };  
      string[] result = intarray.Select(x=>x.ToString()).ToArray();
      

       

      SqlCommand command = new SqlCommand();
      command.Connection = connection;
      command.CommandText = "sp_DeleteMultipleId";
      command.CommandType = CommandType.StoredProcedure;
      command.Parameters.Add("@Id",SqlDbType.VARCHAR).Value=result ;
      

    This will delete multiple rows, All the best

提交回复
热议问题