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

时间:2014-10-15 17:51:28

标签: sql sql-server xml

我有这样的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

2 个答案:

答案 0 :(得分:4)

这比@ Nick的答案容易得多,因为它只需要一个.nodes()来代替三个嵌套的...... {/ p>

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>元素并从中获取属性值

答案 1 :(得分:3)

我是这样做的(虽然有几种方法)。

WITH xmlData AS (
SELECT CAST('<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>' AS XML) as xmlData)
SELECT xmlData, logs.x.value('(@at)[1]','varchar(50)') as 'Element1', logs.x.value('(@lifespan)[1]','varchar(50)') as 'Element2', ismsgs.logs.value('(@direction)[1]','varchar(50)') as 'Element3', fields.ismsgs.value('(@value)[1]','varchar(50)') as 'Element4'
FROM xmlData x
CROSS APPLY xmlData.nodes('root/log') logs(x)   
CROSS APPLY xmlData.nodes('root/log/receive/isomsg') ismsgs(logs)
CROSS APPLY xmlData.nodes('root/log/receive/isomsg/field') fields(ismsgs)