2012-06-08 52 views
2

得到明顯的依賴關係列表中我有一個表task_dependency看起來像下面如何從CTE

task_id depend_task_id 
------------------------- 
1    NULL 
2    NULL 
3    1 
4    2 
4    1 
5    4 
5    3 

我嘗試運行一個查詢來獲取每個任務不同的任務依賴列表(包括任務本身)。

預期輸出(任務列表順序無所謂):

task_id depend_task_list 
----------------------------------------------- 
1  1; 
2  2; 
3  1;3 
4  1;2;4 
5  1;2;3;4;5 

我有什麼到目前爲止

DECLARE @t TABLE (task_id INT, depend_task_id INT) 

INSERT INTO @t VALUES (1, NULL),(2,NULL),(3,1),(4,2),(4,1),(5,4),(5,3) 

;WITH AllDependency (task_id,depend_task_list) 
AS( 
    SELECT 
    task_id, 
    depend_task_list=CAST(task_id AS VARCHAR(4000)) 
    FROM @t 
    WHERE depend_task_id IS NULL 
UNION ALL 
    SELECT 
    t.task_id, 
    depend_task_list= CAST(CAST(t.task_id AS VARCHAR(10)) + ';' + depend_task_list AS VARCHAR(4000)) 
    FROM @t t 
    INNER JOIN AllDependency AS d 
     ON d.task_id = t.depend_task_id 
) 
SELECT 
    task_id, 
    (SELECT depend_task_list + ';' FROM AllDependency d2 WHERE d.task_id = d2.task_id FOR XML PATH('')) AS depend_task_list 
FROM AllDependency d 
GROUP BY task_id 
ORDER BY task_id 

電流輸出:

task_id depend_task_list 
----------------------------------------- 
1   1; 
2   2; 
3   3;1; 
4   4;2;4;1; 
5   5;4;2;5;4;1;5;3;1; 

問: 哪有我得到一個獨特的任務依賴列表而不使用Cursor?

SQLFiddle鏈接http://sqlfiddle.com/#!3/4c034/2

感謝您的任何援助。

回答

3

好吧,試試這個查詢,看看是否有幫助:

DECLARE @t TABLE (task_id INT, depend_task_id INT) 

INSERT INTO @t VALUES (1, NULL),(2,NULL),(3,1),(4,2),(4,1),(5,4),(5,3) 

;WITH CTE AS 
(
    SELECT * 
    FROM @t 
    UNION ALL 
    SELECT A.task_id, B.depend_task_id 
    FROM CTE A 
    INNER JOIN @t B 
    ON A.depend_task_id = B.task_id 
    --WHERE B.depend_task_id IS NOT NULL 
), CTE2 AS 
(
    SELECT DISTINCT task_id, ISNULL(depend_task_id,task_id) depend_task_id 
    FROM CTE 
) 
SELECT t1.task_id, 
     STUFF((SELECT ';' + CAST(t2.depend_task_id AS VARCHAR(5)) 
       FROM CTE2 t2 
       WHERE t2.task_id = t1.task_id 
       ORDER BY depend_task_id 
       FOR XML PATH('')),1,1,'') AS depend_task_list 
FROM CTE2 t1 
GROUP BY task_id 

Here是sqlfiddle測試。

+0

完美!非常感謝你的幫助 – EricZ