TSQL XML查询问题
问题描述:
这是可能的TSQL?TSQL XML查询问题
我通过一个XML参数提供这个结构。我需要将它设置为临时表。
DECLARE @xml xml
SET @xml = '<Events>
<Event id="8">
<Responses>
<Response id="59">
<Loe>
<Id>89</Id>
</Loe>
</Response>
<Response id="60">
<Loe>
<Id>89</Id>
<Id>90</Id>
<Id>88</Id>
<Id>87</Id>
</Loe>
</Response>
</Responses>
</Event>
</Events>';
试图显示它想:
EventId ResponseId LoeId
8 59 89
8 60 89
8 60 90
8 60 88
8 60 87
我试图用这个查询,但它抛出一个错误。
SELECT
[data].value('../../@id','varchar(100)') AS EventId,
[data].value('@id','varchar(100)') AS ResponseId,
[data].value('Loe/Id','varchar(100)') AS LoeId
FROM @xml.nodes('/Events/Event/Responses/Response') as Test([data])
但如果我删除它的工作LoeId,我得到这个:
EventId ResponseId
8 59
8 60
我做错了吗?如何解决查询中的Loe-> Id?
我正在使用MSSQL 2008.你有什么想法吗?
谢谢。
答
这应该这样做:
SELECT
event.value('@id', 'int') AS Event,
response.value('@id','int') AS Response,
id.value('.','int') AS LoeId
FROM
@xml.nodes('Events/Event') AS t1(event) cross apply
t1.event.nodes('Responses/Response') AS t2(response) cross apply
t2.response.nodes('Loe/Id') AS t3(id)
ORDER BY Event, Response, LoeId
你前面的例子中的数据包含了几事件节点,以便将其处理为好 – 2011-04-08 03:28:56
@K伊万诺夫非常感谢你。我很亲密,但很遥远!真棒回答,非常感谢。它真的为我清理了一些东西。 – nitefrog 2011-04-08 04:49:05