SQL 服务器 XML: 如何 Return 所有元素同名?

SQL Server XML: How To Return All Elements With The Same Name?

我将数据存储在 SQL 服务器 XML 列中。每行中的元素并不总是以相同的顺序排列,但我需要 return 所有具有特定名称的元素。在下面的示例中,我如何 return 所有名为 'apple' 的元素?

<!-- Row 1 -->
<store id="3">
    <apple type="tasty" />
    <orange color="grape" />
</store>

<!-- Row 2 -->
<house id="14">
    <banana condition="rotten" />
    <apple type="fuji" />
</house>

<!-- Row 3 -->
<apple>

<!-- Row 4 -->
<country id="3">
    <state id="14">
        <apple type="GSmith" />
    </state>
</country>

使用“//elementName”语法查找名为 "elementName" 的元素,无论它在层次结构中的什么位置。

declare @x xml = '
<x>
<store id="3">
    <apple type="tasty" />
    <orange color="grape" />
</store>

<!-- Row 2 -->
<house id="14">
    <banana condition="rotten" />
    <apple type="fuji" />
</house>

<!-- Row 3 -->
<apple/>

<!-- Row 4 -->
<country id="3">
    <state id="14">
        <apple type="GSmith" />
    </state>
</country>
</x>'

select apple.query('.')
from @x.nodes('//apple') as x(apple)

注意:我不得不稍微修改您的示例 XML 以使其有效。即为所有内容提供一个顶级元素来嵌套并使其成为裸体(因此标签被关闭)。