根据分隔符拆分为多个列

时间:2016-06-09 19:54:11

标签: sql-server-2008

我有一个专栏TASKID" 3.001.2.2.1.3"

我根据.(点)将它们拆分为4列,每列值为:

TaskLevel1=3                   
TaskLevel2=3.001         
TaskLevel3=3.001.2      
TaskLevel4=3.001.2.2

用于创建表和插入脚本的示例代码如下:

CREATE TABLE [dbo].[Task]
(
    [TaskID] [varchar](35) NULL,
    [TaskLevel1] [varchar](35) NULL,
    [TaskLevel2] [varchar](35) NULL,
    [TaskLevel3] [varchar](35) NULL,
    [TaskLevel4] [varchar](35) NULL
)


INSERT [dbo].[Task] ([TaskID], [TaskLevel1], [TaskLevel2], [TaskLevel3], [TaskLevel4]) 
VALUES (N'3.001.2.2.1', N'3', N'3.001', N'3.001.2', N'3.001.2.2')

INSERT [dbo].[Task] ([TaskID], [TaskLevel1], [TaskLevel2], [TaskLevel3], [TaskLevel4]) 
VALUES (N'3.001.2.2.1.3', N'3', N'3.001', N'3.001.2', N'3.001.2.2')

1 个答案:

答案 0 :(得分:0)

DECLARE @T TABLE (
     [TaskID] [varchar](35) NULL
)

INSERT INTO @T VALUES
('3'),
('3.001'),
('3.001.2.2.1'),
('3.001.2.2.1.3')

;with cte([TaskID], [start], [level]) as
(
    SELECT [TaskID], 1, 1
    FROM @t
    UNION ALL
    SELECT [TaskID], CHARINDEX('.', [TaskID], [start]) + 1, [level] + 1
    FROM cte
    WHERE CHARINDEX('.', [TaskID], [start]) > 0
),
cte2 as 
(
    SELECT [TaskID], LEFT([TaskID], CHARINDEX('.', [TaskID] + '.', [start]) - 1) AS [val], [level] 
    FROM cte
)
SELECT [TaskID]
    , [1] AS [TaskLevel1] 
    , [2] AS [TaskLevel2]
    , [3] AS [TaskLevel3]
    , [4] AS [TaskLevel4]
FROM cte2
PIVOT (MAX([val])
        FOR [level] IN ([1], [2], [3], [4])) p
ORDER BY [TaskID]