Search code examples
sqlsql-server-2005stored-procedures

Passing an array of parameters to a stored procedure


I need to pass an array of "id's" to a stored procedure, to delete all rows from the table EXCEPT the rows that match id's in the array.

How can I do it in a most simple way?


Solution

  • Use a stored procedure:

    EDIT: A complement for serialize List (or anything else):

    List<string> testList = new List<int>();
    
    testList.Add(1);
    testList.Add(2);
    testList.Add(3);
    
    XmlSerializer xs = new XmlSerializer(typeof(List<int>));
    MemoryStream ms = new MemoryStream();
    xs.Serialize(ms, testList);
    
    string resultXML = UTF8Encoding.UTF8.GetString(ms.ToArray());
    

    The result (ready to use with XML parameter):

    <?xml version="1.0"?>
    <ArrayOfInt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <int>1</int>
      <int>2</int>
      <int>3</int>
    </ArrayOfInt>
    

    ORIGINAL POST:

    Passing XML as parameter:

    <ids>
        <id>1</id>
        <id>2</id>
    </ids>
    

    CREATE PROCEDURE [dbo].[DeleteAllData]
    (
        @XMLDoc XML
    )
    AS
    BEGIN
    
    DECLARE @handle INT
    
    EXEC sp_xml_preparedocument @handle OUTPUT, @XMLDoc
    
    DELETE FROM
        YOURTABLE
    WHERE
        YOUR_ID_COLUMN NOT IN (
            SELECT * FROM OPENXML (@handle, '/ids/id') WITH (id INT '.') 
        )
    EXEC sp_xml_removedocument @handle