在SQL中查询XML文档

时间:2011-04-01 18:25:47

标签: xml sql-server-2005

我从我正在处理的一个相当大的XML文件中获得了以下代码:

<Product id="4161" removed="false">
    <NativeReviewStatistics>
        <AverageRatingValues>
            <AverageRatingValue>
                <AverageRating>3.0</AverageRating>
                <RatingDimension>
                    <ExternalId>Quality</ExternalId>
                    <RatingRange>5</RatingRange>
                </RatingDimension>
            </AverageRatingValue>
            <AverageRatingValue>
                <AverageRating>4.0</AverageRating>
                <RatingDimension>
                    <ExternalId>Value</ExternalId>
                    <RatingRange>5</RatingRange>
                </RatingDimension>
            </AverageRatingValue>
        </AverageRatingValues>
    </NativeReviewStatistics>
</Product>

我希望获得最终结果,其行如下所示:

ProductId | ExternalId | AveRating | RatingRange
4161        Quality      3.0         5
4161        Value        4.0         5

到目前为止,我已经得到了这个:

    SELECT  feed.product.value('@id[1]', 'INT') AS ProductId
    FROM    @xmlData.nodes('/Feed/Product') feed ( product )

但我对这里的去向感到有点难过。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

SELECT
    feed.product.value('@id[1]', 'INT') AS ProductId,
    step3.data.value('ExternalId[1]', 'varchar(50)') AS ExternalId,
    step2.data.value('AverageRating[1]', 'decimal(10,1)') AS AveRating,
    step3.data.value('RatingRange[1]', 'int') AS RatingRange
FROM
    @xmlData.nodes('/Feed/Product') feed ( product )
CROSS APPLY
    feed.product.nodes('NativeReviewStatistics/AverageRatingValues/AverageRatingValue') step2(data)
CROSS APPLY    
    step2.data.nodes('RatingDimension')  step3(data)