将多个逗号分隔列拆分为行

时间:2018-05-23 07:45:24

标签: sql sql-server tsql

我有一个表(SQL Server),它在多个列中包含逗号分隔值,如下所示:

Rule_ID    ListType_ID    Values
1          1,2            100,200
2          3,4            300,400

我想拆分逗号分隔值并将它们转换为行。

所需的输出必须如下所示:

Rule_ID    ListType_ID    Values
1          1              100
1          2              200
2          3              300
2          4              400

我尝试过以下查询:

DECLARE @TEMP AS TABLE (
    [Rule_ID] INT,
    [ListType_ID] VARCHAR(MAX),
    [Values] VARCHAR(MAX)
)

INSERT INTO @TEMP
SELECT 1, '1,2', '100,200'
UNION ALL
SELECT 2, '3,4', '300,400' 

SELECT 
    [Rule_ID],
    PARSENAME(REPLACE(Split1.b.value('.', 'VARCHAR(100)'),'-','.'),1) AS [ListType_ID],
    PARSENAME(REPLACE(Split.a.value('.', 'VARCHAR(100)'),'-','.'),1) AS [Values] 
FROM  
(
    SELECT [Rule_ID],
    CAST ('<M>' + REPLACE([ListType_ID], ',', '</M><M>') + '</M>' AS XML) AS [ListType_ID],
    CAST ('<M>' + REPLACE([Values], ',', '</M><M>') + '</M>' AS XML) AS [Values] 
    FROM @TEMP     
) AS A 
CROSS APPLY [Values].nodes ('/M') AS Split(a)
CROSS APPLY [ListType_ID].nodes ('/M') AS Split1(b)
ORDER BY [Rule_ID], [ListType_ID], [Values]

此查询返回以下输出,该输出与所需输出不同:

Rule_ID    ListType_ID    Values
1          1              100
1          1              200
1          2              100
1          2              200
2          3              300
2          3              400
2          4              300
2          4              400

请在这帮助我...... !!!!

1 个答案:

答案 0 :(得分:4)

请检查以下SQL脚本

要在SQL中拆分字符串,我使用了以下用户定义的SQL split string functions

之一

这些函数返回我在WHERE子句中使用的splitted字符串的顺序,因此我可以一对一地映射字段值

/*
create table Table_1 (
    Rule_ID int,    ListType_ID    varchar(max), [Values] varchar(max)
)
insert into Table_1 select 1,'1,2','100,200'
insert into Table_1 select 2,'3,4','300,400'
*/
select 
Rule_ID,
idlist.val as ListType_ID,
valueslist.val as [Values]
from Table_1
cross apply dbo.SPLIT(ListType_ID,',') as idlist
cross apply dbo.SPLIT([Values],',') as valueslist
where 
idlist.id = valueslist.id