How to use CROSS APPLY XML PATH
-
26-10-2019 - |
Question
How can I use CROSS APPLY
and FOR XML
to normalise the table which contains a list for informartion?
Product Orderid
P1 1,2,3
P2 1,3
P3 1
It should be normalised like below
P1 1
P1 2
P1 3
P2 1
P2 3
P3 1
I think it can be done with CROSS APPLY FOR XML
. Is there any other way of doing it?
Solution
This is tested and working:
SELECT * INTO #T
FROM (
SELECT 'P1' Product, '1,2,3' OrderId
UNION SELECT 'P2', '1,3'
UNION SELECT 'P3', '1') x;
WITH S AS (
SELECT product, x.t
FROM #T cross apply
(select convert(xml, N'<root><r>' + replace(orderid,',','</r><r>') + '</r></root>') t) x
)
SELECT s.Product, r.value('.', 'int') OrderId
FROM s cross apply t.nodes('//root/r') as records(r);
DROP TABLE #T;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow