I have an xml column in my SQL Server database that has records in the following format
<items>
<item>
<data alias="Number">123N</data>
<data alias="Description">4 sq.mm Feed Through Terminal block in Grey colour</data>
<data alias="Standard Packing Quantity">100</data>
</item>
<item>
<data alias="Number">234N</data>
<data alias="Description">Toy</data>
<data alias="Standard Packing Quantity">100</data>
</item>
<item>
<data alias="Number">579N</data>
<data alias="Description">Doll</data>
<data alias="Standard Packing Quantity">100</data>
</item>
<item>
<data alias="Catalouge Number">234</data>
<data alias="Description">Vehicle</data>
<data alias="Standard Packing Quantity">324234</data>
</item>
</items>
So to extract the data here I use:
SELECT
CatalogueNo,Description,StdPackingQty
from
(select
CAST(xml as xml).query('//data alias=''Description'']').value('.','nvarchar(225)') [Description],
CAST(xml as xml).query('//data [@alias=''Catalouge Number'']')
.value('.','nvarchar(225)')[CatalogueNo],
CAST(xml as xml).query('//data [@alias=''Standard Packing Quantity'']').value('.','nvarchar(225)')[StdPackingQty]
from [dbo].[cmsContentXml] )as hierarchy
Where CatalogueNo is not null
The problem I face is that the data that is extracted is all concatenated.
I need data in separate rows for each item,so the data needs to be in 3
columns and 4 rows.
Kindly help me resolve the issue asap and help write a query that would fetch data
free of concat
You can use
Cross Applyto breakdown the XML into separate data rows, and pull the data from those:Note: I’ve remmed out the where clause at the end as it will reduce you to just one row, whereas the question state you want 4 rows as the result.