简体   繁体   中英

How to transform XML data into SQL Server table (part 2)

I have asked a question similar to this one. But this time I need to transpose the data.

I have a XML data like this :

<root>
 <log realm="ABC" at="Wed Oct 15 00:00:02 2014.211" lifespan="2279ms">
  <receive>
    <isomsg direction="IN">
      <header>6000911384</header>
      <field id="0" value="0800"/>
      <field id="3" value="980000"/>
      <field id="11" value="000852"/>
    </isomsg>
  </receive>
</log>
</root>

is it possible to transform that XML data into table like this :

AT             |lifespan|direction |ID_0 |ID_3  |ID_11
-------------------------------------------------------
Wed Oct 15 2014|2279ms  |in        |0800 |980000|000852

Please help, thank you all

This unpacks your specific data into the result set you've asked for, but how reusable this is depends a lot on what other pieces of XML you might want to unpack:

declare @inp xml = '<root>
 <log realm="ABC" at="Wed Oct 15 00:00:02 2014.211" lifespan="2279ms">
  <receive>
    <isomsg direction="IN">
      <header>6000911384</header>
      <field id="0" value="0800"/>
      <field id="3" value="980000"/>
      <field id="11" value="000852"/>
    </isomsg>
  </receive>
</log>
</root>'

select
    n.value('@at','varchar(10)') + SUBSTRING(n.value('@at','varchar(30)'),20,5) as AT,
    n.value('@lifespan','varchar(20)') as lifespan,
    n.value('receive[1]/isomsg[1]/@direction','varchar(10)') as direction,
    n.value('receive[1]/isomsg[1]/field[@id="0"][1]/@value','varchar(10)') as id_0,
    n.value('receive[1]/isomsg[1]/field[@id="3"][1]/@value','varchar(10)') as id_3,
    n.value('receive[1]/isomsg[1]/field[@id="11"][1]/@value','varchar(10)') as id_11
from @inp.nodes('/root/log') n(n)

Result:

AT              lifespan             direction  id_0       id_3       id_11
--------------- -------------------- ---------- ---------- ---------- ----------
Wed Oct 15 2014 2279ms               IN         0800       980000     000852

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