Blog blurb

This blog is the resting place of my various projects. It's a place to find out about my various commercial and personal projects. Some of them are quite geeky and some of them are more arts based.

RSS Get updates by subscribing to the RSS feed.

Sending a list into an SQL stored procedure using XML

01 June 2007

I wanted to pass a list of user IDs into a stored procedure. What I really wanted was to be able to pass an array, but you're not able to do that because it would be too easy. It took me quite a while to figure this out, but now I know how, it'll be easy next time.

There's a nice set of functions that allow you to get values from an XML string and treat the set of values like a table. Just what I wanted from arrays really.

Here is the XML string that I used:

<users><user id="24" /><user id="27" /></users>

And here is the relevant part of the stored procedure I made:

CREATE PROCEDURE pXmlTest
  -- Parameters
  @xmlStr varchar(255)
  AS
  BEGIN
    SET NOCOUNT ON;

    DECLARE @xmlHandle int;

    -- Prepare XML document and get a handle for it
    exec sp_xml_preparedocument @xmlHandle OUTPUT, @xmlStr;

    -- You can now use the OPENXML function which returns a rowset that behaves like a table
    -- WITH chooses the field names you want to use from the XML and declares the type they will be.
    SELECT * FROM tUsers WHERE id IN
    ( SELECT id FROM OPENXML(@xmlHandle, '/users/user') WITH (id varchar(50)) );
  END

Richard Garside Richard&#32;Garside (gravatar)
Tags:

0 Comments

leave your own
Your Information

email saved for notifications but never distributed

your comment