简体   繁体   English

如何将XML数据转换为SQL Server表(第2部分)

[英]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 : 我有这样的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>

is it possible to transform that XML data into table like this : 是否可以像这样将XML数据转换为表:

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: 这会将您的特定数据解压缩到您要求的结果集中,但是它的可重用性在很大程度上取决于您可能希望解压缩的其他XML片段:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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