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
  • 2,952
  • 3
  • 28
  • 45
Shine
  • 1,373
  • 3
  • 14
  • 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
  • 132,594
  • 21
  • 199
  • 273
Yuck
  • 47,217
  • 13
  • 101
  • 134