1

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?

Michael J Swart
  • 3,060
  • 3
  • 29
  • 46
Shine
  • 1,413
  • 3
  • 15
  • 18

1 Answers1

1

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;
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281
Yuck
  • 49,664
  • 13
  • 105
  • 135