我将数据存储在SQL Server XML列中。每行中的元素并不总是以相同的顺序,但我需要返回具有特定名称的所有元素。鉴于以下示例,我将如何返回名为' 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>
答案 0 :(得分:2)
使用“// 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才能使其有效。即为所有嵌入并使裸体嵌入的所有物品提供顶级元素(因此标签已关闭)。