简体   繁体   中英

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

I have data stored in an SQL Server XML column. 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'?

<!-- 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.

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. Namely providing a top-level element for everything to nest under and making the naked into (so the tag is closed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM