简体   繁体   中英

Extract XML data in tabular format from Sql Server

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>

I am not able to extract data from above xml data field. I need an output in which data is saved in two columns ie itemid and unitprice

Edit - Replaced answer with tested sql. Also see 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM