我问了一个与此类似的问题。但这次我需要转置数据。
我有这样的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_0 |ID_3 |ID_11
-------------------------------------------------------
Wed Oct 15 2014|2279ms |in |0800 |980000|000852
请帮助,谢谢大家
答案 0 :(得分:1)
这会将您的特定数据解压缩到您要求的结果集中,但这有多可重复使用取决于您可能要解压缩的其他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)
结果:
AT lifespan direction id_0 id_3 id_11
--------------- -------------------- ---------- ---------- ---------- ----------
Wed Oct 15 2014 2279ms IN 0800 980000 000852