Search code examples
sql-serverxmlsql-server-2012openxmlsql-server-openxml

Get rows from XML array using OPENXML


I have following XML:

<root>
  <fields>
    <field>Some Name</field>
    <field>Another Name</field>
  </fields>
</root>

As the result I would like to have:

Some Name
Another Name

To achieve that I am trying to execute following query:

DECLARE @XML XML = N'
<root>
  <fields>
    <field>Some Name</field>
    <field>Another Name</field>
  </fields>
</root>';


DECLARE @idoc INT;
EXEC sys.sp_xml_preparedocument @idoc OUTPUT, @XML;
SELECT  *
FROM    OPENXML(@idoc, '/root/fields',2)
WITH (Name VARCHAR(300)  './field');
EXEC sys.sp_xml_removedocument @idoc;

But I am getting only the first record...


Solution

  • DECLARE @XML XML = N'
    <root>
      <fields>
        <field>Some Name</field>
        <field>Another Name</field>
      </fields>
    </root>';
    
    -- XQuery
    SELECT t.c.value('(./text())[1]', 'VARCHAR(300)')
    FROM @XML.nodes('/root/fields/field') t(c)
    
    -- OpenXML
    DECLARE @idoc INT
    EXEC sys.sp_xml_preparedocument @idoc OUTPUT, @XML
    
    SELECT *
    FROM OPENXML(@idoc, '/root/fields/*',2) WITH (Name VARCHAR(300) '.')
    
    EXEC sys.sp_xml_removedocument @idoc