加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何将XML数据转换为SQL Server表

发布时间:2020-12-16 22:41:31 所属栏目:百科 来源:网络整理
导读:我有这样的 XML数据: root log realm="ABC" at="Wed Oct 15 00:00:02 2014.211" lifespan="2279ms" receive isomsg direction="IN" header6000911384/header field id="0" value="0800"/ field id="3" value="980000"/ field id="11" value="000852"/ /isom
我有这样的 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>

如何将XML数据转换为表格,如下所示:

AT         |lifespan|direction |ID |Value 
---------------------------------------------
Wed Oct 15 2014|2279ms  |in        |0  |0800
Wed Oct 15 2014|2279ms  |in        |3  |980000
Wed Oct 15 2014|2279ms  |in        |11 |000852

解决方法

这比@ Nick的答案容易得多,因为它只需要一个.nodes()调用而不是三个嵌套的调用…

DECLARE @input 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
    At = xc.value('../../../@at','varchar(50)'),Lifespan = xc.value('../../../@lifespan','varchar(25)'),Direction = xc.value('../@direction','varchar(10)'),ID = XC.value('@id','int'),Value = xc.value('@value','varchar(25)')
FROM
    @Input.nodes('/root/log/receive/isomsg/field') AS XT(XC)

对@Input.nodes的调用基本上返回XML片段的“虚拟”表,表示< field>中的每一个. XML元素.通过使用..我们还可以导航原始文档中的“向上”XML层次结构以访问< isomsg>和< log>元素和从中获取属性值

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读