使用OPENXML从XML数组中获取行

时间:2016-06-03 10:43:18

标签: sql-server xml sql-server-2012 openxml sql-server-openxml

我有以下XML:

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

结果我希望:

Some Name
Another Name

要实现这一点,我正在尝试执行以下查询:

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;

但我只获得了第一张唱片......

1 个答案:

答案 0 :(得分:4)

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