开发者

TSQL XML Query Question

Is this possible in TSQL?

I am feeding this structure in via an xml param. And I need to set it into a temp table.

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>';

Trying to display it like:

EventId    ResponseId     LoeId
8          59             89
8          60             89
8          60             90开发者_如何学Go
8          60             88
8          60             87

I tried to use this query, but it throws an error.

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])

But if I remove the LoeId it works and I get this:

EventId    ResponseId
8          59             
8          60             

What I am doing wrong? How do I address the Loe->Id in the query?

I am using MSSQL 2008. Do you have any ideas?

Thanks.


this should do it:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜