Search code examples
sql-servert-sqlrowset

Do I need to use T-SQL Rowset?


So I'm trying to convert a web service that was an Oracle application to T-SQL. The fun part is I only have the web service code and no database code at all. I see there is an input parameter that contains <ROWSET><ROW NUM=\"1\"><TRANSACTIONID>123456</TRANSACTIONID></ROW></ROWSET>

I'm looking through the docs for T-SQL and I can't seem to find anything helpful on what I can do with this xml. From what I can understand it's used to insert values into a table since the elements will not be similar in every call.

Any help would be appreciated.


Solution

  • Assuming this XML is a parameter to your T-SQL stored proc or function, you can use the OPENXML utility to work with this type of data. Here's a complete example (reposted here for clarity):

    DECLARE @idoc int
    DECLARE @doc varchar(1000)
    SET @doc ='
    <people>
      <person id="1">
        <firstname>John</firstname>
        <surname>Doe</surname>
      </person>
      <person id="2">
        <firstname>Mary</firstname>
        <surname>Jane</surname>
      </person>
    </people>
    '
    /* Create an internal representation of the XML document */
    EXEC sp_xml_preparedocument @idoc OUTPUT, @doc
    -- Execute a SELECT statement that uses the OPENXML rowset provider.
    SELECT    *
    FROM       OPENXML (@idoc, '/people/person',1)
                WITH (id varchar(20),
                      firstname varchar(20) 'firstname',
                      surname varchar(20) 'surname')
    EXECUTE sp_xml_removedocument @idoc
    

    Result:

    id  firstname       surname
    1   John            Doe
    2   Mary            Jane