这在TSQL中是否可行?
我通过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-&gt; Id?
我正在使用MSSQL 2008.你有什么想法吗?
感谢。
答案 0 :(得分:3)
这应该这样做:
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