我有这样的 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"
<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>元素和从中获取属性值
