从Sql Server中以表格格式提取XML数据

时间:2018-10-15 11:02:02

标签: sql sql-server xml tsql

How can i extract xml data in tabular format in Sql Server. the sample xml field is something like this

<?xml version='1.0' encoding='UTF-8'?>
<root>
    <element1>
        <Header Client_ID="100" Sent_date_time="2015-03-02T9:30:43.808-06:00"/>
        <element2>
            <element3 UnitPrice="3.2" ItemID="njh1"/>
            <element3 UnitPrice="4.1" ItemID="ole5"/>
            <element3 UnitPrice="4.6" ItemID="usd3"/>
            <element3 UnitPrice="8.2" ItemID="eor9"/>
            <element3 UnitPrice="2.9" ItemID="abc8"/>
            <element3 UnitPrice="5.1" ItemID="gfd3"/>
            <element3 UnitPrice="4.9" ItemID="kdu0"/>
            <element3 UnitPrice="6.1" ItemID="uso8"/>
        </element2>
    </element1>
</root>

我无法从上述xml数据字段中提取数据。我需要一个输出,其中数据保存在两列中,即itemid和unitprice

1 个答案:

答案 0 :(得分:0)

编辑-已测试的sql替换了答案。另请参见XQuery Language Reference (SQL Server)

CREATE TABLE xml_table (column1 xml);

INSERT INTO xml_table (column1) values ('<?xml version=''1.0'' encoding=''UTF-8''?>
<root>
    <element1>
        <Header Client_ID="100" Sent_date_time="2015-03-02T9:30:43.808-06:00"/>
        <element2>
            <element3 UnitPrice="3.2" ItemID="njh1"/>
            <element3 UnitPrice="4.1" ItemID="ole5"/>
            <element3 UnitPrice="4.6" ItemID="usd3"/>
            <element3 UnitPrice="8.2" ItemID="eor9"/>
            <element3 UnitPrice="2.9" ItemID="abc8"/>
            <element3 UnitPrice="5.1" ItemID="gfd3"/>
            <element3 UnitPrice="4.9" ItemID="kdu0"/>
            <element3 UnitPrice="6.1" ItemID="uso8"/>
        </element2>
    </element1>
</root>');

SELECT e3.p.value('(@UnitPrice)[1]', 'varchar(100)')
FROM   xml_table
CROSS APPLY column1.nodes('/root/element1/element2/element3') as e3(p)