[英]SQL Server XML: How To Return All Elements With The Same Name?
I have data stored in an SQL Server XML column. 我将数据存储在SQL Server XML列中。 The elements in each row are not always in the same order but I need to return all elements that have a certain name.
每行中的元素并不总是相同的顺序,但是我需要返回所有具有特定名称的元素。 Given the example below, how would I return all elements named 'apple'?
给定以下示例,我将如何返回所有名为“ 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>
Use the "//elementName" syntax to find an element called "elementName" regardless of where it is in the hierarchy. 使用“ // 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)
NB: I had to modify your example XML slightly to make it valid. 注意:我必须稍微修改您的示例XML以使其有效。 Namely providing a top-level element for everything to nest under and making the naked into (so the tag is closed).
即为所有要嵌套的东西提供裸露的顶层元素(使标签封闭)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.