2016-06-09 61 views
0

我有一個柱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') 
+0

,什麼是你想要的結果? – Lamak

+0

我必須將第一列TASKID分成四列,值爲** TaskLevel1 = 3 TaskLevel2 = 3.001 TaskLevel3 = 3.001.2 TaskLevel4 = 3.001.2.2 ** – SuperKings

+0

此格式是否始終保持不變? '#######....' – scsimon

回答

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]