我正在尝试插入XML字符串 1,2,3,4,5,6,7,8,9,1,1,1,1,2,23,4 进入表
我想以这样的方式将数据插入到下表中,即每3个值之后它应该进入下一行是否可以这样做? 并在程序中生成xml字符串。
答案 0 :(得分:2)
您的问题很不清楚,但您可能正在寻找类似的内容:
DECLARE @Numbers VARCHAR(MAX)='1,2,3,4,5,6,7,8,9,,1,1,1,1,2,23,4';
WITH Splitted AS
(
SELECT A.B.value('.','int') AS Number
,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowInx
FROM (SELECT CAST('<x>' + REPLACE(@Numbers,',','</x><x>') + '</x>' AS XML)) AS Casted(AsXml)
CROSS APPLY Casted.AsXml.nodes('/x') AS A(B)
)
,Extended AS
(
SELECT (RowInx -1 ) / 3 AS Rank3
,Number
,REPLACE('Field_' + CAST((RowInx % 3) AS VARCHAR(1)),'_0','_3') AS ColumnName
FROM Splitted
)
SELECT p.*
FROM Extended
PIVOT
(
MAX(Number) FOR ColumnName IN(Field_1,Field_2,Field_3)
) AS p
结果(btw:示例中的空值“... 8,9 ,, 1,1”被视为“0”):
Rank3 Field_1 Field_2 Field_3
0 1 2 3
1 4 5 6
2 7 8 9
3 0 1 1
4 1 1 2
5 23 4 NULL