How to pass an array into a SQL Server stored procedure

前端 未结 11 2430
轻奢々
轻奢々 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:51

    There is no support for array in sql server but there are several ways by which you can pass collection to a stored proc .

    1. By using datatable
    2. By using XML.Try converting your collection in an xml format and then pass it as an input to a stored procedure

    The below link may help you

    passing collection to a stored procedure

    0 讨论(0)
  • 2020-11-21 23:54

    SQL Server 2008 (or newer)

    First, in your database, create the following two objects:

    CREATE TYPE dbo.IDList
    AS TABLE
    (
      ID INT
    );
    GO
    
    CREATE PROCEDURE dbo.DoSomethingWithEmployees
      @List AS dbo.IDList READONLY
    AS
    BEGIN
      SET NOCOUNT ON;
    
      SELECT ID FROM @List; 
    END
    GO
    

    Now in your C# code:

    // Obtain your list of ids to send, this is just an example call to a helper utility function
    int[] employeeIds = GetEmployeeIds();
    
    DataTable tvp = new DataTable();
    tvp.Columns.Add(new DataColumn("ID", typeof(int)));
    
    // populate DataTable from your List here
    foreach(var id in employeeIds)
        tvp.Rows.Add(id);
    
    using (conn)
    {
        SqlCommand cmd = new SqlCommand("dbo.DoSomethingWithEmployees", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter tvparam = cmd.Parameters.AddWithValue("@List", tvp);
        // these next lines are important to map the C# DataTable object to the correct SQL User Defined Type
        tvparam.SqlDbType = SqlDbType.Structured;
        tvparam.TypeName = "dbo.IDList";
        // execute query, consume results, etc. here
    }
    

    SQL Server 2005

    If you are using SQL Server 2005, I would still recommend a split function over XML. First, create a function:

    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, '<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
      );
    GO
    

    Now your stored procedure can just be:

    CREATE PROCEDURE dbo.DoSomethingWithEmployees
      @List VARCHAR(MAX)
    AS
    BEGIN
      SET NOCOUNT ON;
    
      SELECT EmployeeID = Item FROM dbo.SplitInts(@List, ','); 
    END
    GO
    

    And in your C# code you just have to pass the list as '1,2,3,12'...


    I find the method of passing through table valued parameters simplifies the maintainability of a solution that uses it and often has increased performance compared to other implementations including XML and string splitting.

    The inputs are clearly defined (no one has to guess if the delimiter is a comma or a semi-colon) and we do not have dependencies on other processing functions that are not obvious without inspecting the code for the stored procedure.

    Compared to solutions involving user defined XML schema instead of UDTs, this involves a similar number of steps but in my experience is far simpler code to manage, maintain and read.

    In many solutions you may only need one or a few of these UDTs (User defined Types) that you re-use for many stored procedures. As with this example, the common requirement is to pass through a list of ID pointers, the function name describes what context those Ids should represent, the type name should be generic.

    0 讨论(0)
  • 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, '<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
        );
      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

    0 讨论(0)
  • 2020-11-22 00:00

    You need to pass it as an XML parameter.

    Edit: quick code from my project to give you an idea:

    CREATE PROCEDURE [dbo].[GetArrivalsReport]
        @DateTimeFrom AS DATETIME,
        @DateTimeTo AS DATETIME,
        @HostIds AS XML(xsdArrayOfULong)
    AS
    BEGIN
        DECLARE @hosts TABLE (HostId BIGINT)
    
        INSERT INTO @hosts
            SELECT arrayOfUlong.HostId.value('.','bigint') data
            FROM @HostIds.nodes('/arrayOfUlong/u') as arrayOfUlong(HostId)
    

    Then you can use the temp table to join with your tables. We defined arrayOfUlong as a built in XML schema to maintain data integrity, but you don't have to do that. I'd recommend using it so here's a quick code for to make sure you always get an XML with longs.

    IF NOT EXISTS (SELECT * FROM sys.xml_schema_collections WHERE name = 'xsdArrayOfULong')
    BEGIN
        CREATE XML SCHEMA COLLECTION [dbo].[xsdArrayOfULong]
        AS N'<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
        <xs:element name="arrayOfUlong">
            <xs:complexType>
                <xs:sequence>
                    <xs:element maxOccurs="unbounded"
                                name="u"
                                type="xs:unsignedLong" />
                </xs:sequence>
            </xs:complexType>
        </xs:element>
    </xs:schema>';
    END
    GO
    
    0 讨论(0)
  • 2020-11-22 00:04

    It took me a long time to figure this out, so in case anyone needs it...

    This is based on the SQL 2005 method in Aaron's answer, and using his SplitInts function (I just removed the delim param since I'll always use commas). I'm using SQL 2008 but I wanted something that works with typed datasets (XSD, TableAdapters) and I know string params work with those.

    I was trying to get his function to work in a "where in (1,2,3)" type clause, and having no luck the straight-forward way. So I created a temp table first, and then did an inner join instead of the "where in". Here is my example usage, in my case I wanted to get a list of recipes that don't contain certain ingredients:

    CREATE PROCEDURE dbo.SOExample1
        (
        @excludeIngredientsString varchar(MAX) = ''
        )
    AS
        /* Convert string to table of ints */
        DECLARE @excludeIngredients TABLE (ID int)
        insert into @excludeIngredients
        select ID = Item from dbo.SplitInts(@excludeIngredientsString)
    
        /* Select recipies that don't contain any ingredients in our excluded table */
       SELECT        r.Name, r.Slug
    FROM            Recipes AS r LEFT OUTER JOIN
                             RecipeIngredients as ri inner join
                             @excludeIngredients as ei on ri.IngredientID = ei.ID
                             ON r.ID = ri.RecipeID
    WHERE        (ri.RecipeID IS NULL)
    
    0 讨论(0)
提交回复
热议问题