如何使用CROSS APPLY
和FOR XML
规范包含信息列表的表格?
Product Orderid
P1 1,2,3
P2 1,3
P3 1
它应该像下面这样标准化
P1 1
P1 2
P1 3
P2 1
P2 3
P3 1
我认为可以用CROSS APPLY FOR XML
. 还有其他方法吗?
如何使用CROSS APPLY
和FOR XML
规范包含信息列表的表格?
Product Orderid
P1 1,2,3
P2 1,3
P3 1
它应该像下面这样标准化
P1 1
P1 2
P1 3
P2 1
P2 3
P3 1
我认为可以用CROSS APPLY FOR XML
. 还有其他方法吗?
这是经过测试和工作的:
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;