0

例子:

DECLARE @XML XML = '
<Items>
    <document id="doc1" value="100">
        <details>
            <detail detailID="1" detailValue="20"/>
            <detail detailID="2" detailValue="80"/>
        </details>
    </document>
    <document id="doc2" value="0">
        <details>
        </details>
    </document>
</Items>
'

我想要这样的结果:

id    value    detailID   detailValue
doc1  100      1          20
doc1  100      2          80
doc2  0        NULL       NULL

试过:

SELECT document.value('../../@docID', 'VARCHAR(10)') AS 'docID',
       document.value('../../@value', 'INT') AS 'value',
       document.value('@detailID', 'VARCHAR(10)') AS 'detailID',
       document.value('@detailValue', 'INT') AS 'detailValue'
FROM   @XML.nodes('Items/document/details/detail') AS Documents(document)

但是,doc2 没有列出......另外,尝试使用 CROSS JOIN 和 INNER JOIN,但性能非常糟糕。

4

2 回答 2

4

尝试这个:

SELECT document.value('@id', 'VARCHAR(10)') AS docID,
       document.value('@value', 'INT') AS value,
       Detail.value('@detailID', 'INT') as DetailId,
       Detail.value('@detailValue', 'INT') as DetailValue
FROM   @XML.nodes('Items/document') AS Documents(document)
       outer apply Documents.document.nodes('details/detail') as Details(Detail);
于 2013-03-28T18:03:12.403 回答
1

只需添加一个细节:

@XML.nodes('//whatever_depth') AS Documents(document)

使用 '//' 允许您不直接从 root 查询

问候,丹尼斯

于 2014-06-19T08:46:42.027 回答