Given the following XML (in an SQL column field called ‘xfield’):
<data>
<section>
<item id="A">
<number>987</number>
</item>
<item id="B">
<number>654</number>
</item>
<item id="C">
<number>321</number>
</item>
</section>
<section>
<item id="A">
<number>123</number>
</item>
<item id="B">
<number>456</number>
</item>
<item id="C">
<number>789</number>
</item>
</section>
</data>
How do you obtain the following table structure (with A, B & C as the column names):
A | B | C
987|654|321
123|456|789
Using SQL XQuery, I’m trying this (not surprisingly, it’s invalid):
SELECT
data.value('(./section/item[@ID = "A"]/number/[1])', 'int') as A,
data.value('(./section/item[@ID = "B"]/number/[1])', 'int') as B,
data.value('(./section/item[@ID = "C"]/number/[1])', 'int') as C
FROM Table CROSS APPLY [xfield].nodes('/data') t(data)
You’re nearly there.
You need to use
nodes()to shred the xml into the rows you want to work with – here, you want a resultset row for eachsectionelement, so shred withOnce you’ve done that, you just need to make your xpath
[1]syntactically correct (and relative to thesectionnodes you will be ‘in’):And voila: