2009-02-25 87 views
13

我可以在分層數據模型中找到給定記錄的所有子代(請參見下面的代碼),但我不確定如何使用給定的子ID遍歷父/子鏈。任何人都可以指出我在正確的方向弄清楚如何做到這一點?這在LINQ to SQL中可能嗎?CTE可以遍歷層次?

WITH TaskHierarchy (TaskID, [Subject], ParentID, HierarchyLevel, HierarchyPath) AS 
(
    -- Base case 
    SELECT 
     TaskID, 
     [Subject], 
     ParentID, 
     1 as HierarchyLevel, 
     CONVERT(VARCHAR(MAX),'/') AS HierarchyPath 
    FROM Task 
    WHERE TaskID = 2 

    UNION ALL 

    -- Recursive step 
    SELECT 
     t.TaskID, 
     t.Subject, 
     t.ParentID, 
     th.HierarchyLevel + 1 AS HierarchyLevel, 
     CONVERT(varchar(MAX),th.HierarchyPath + CONVERT(VARCHAR(32),t.ParentID) + '/') AS HierarchyPath 
    FROM Task t 
     INNER JOIN TaskHierarchy th ON 
     t.ParentID = th.TaskID 
) 

SELECT * 
FROM TaskHierarchy 
ORDER BY HierarchyLevel, [Subject] 

回答

22

啊,我想通了:

WITH Hierarchy(TaskID, [Subject], ParentID, IsProject, HLevel) 
AS 
(
    SELECT 
     TaskID, 
     [Subject], 
     ParentID , 
     IsProject, 
     0 as HLevel 
    FROM 
     Task 
    WHERE 
     TaskID = 59 

    UNION ALL 

    SELECT 
     SubDepartment.TaskID, 
     SubDepartment.[Subject], 
     SubDepartment.ParentID , 
     SubDepartment.IsProject, 
     HLevel + 1 
    FROM 
     Task SubDepartment 
    INNER JOIN 
     Hierarchy ParentDepartment 
    ON 
     SubDepartment.TaskID = ParentDepartment.ParentID 
) 

SELECT 
    TaskID, 
    [Subject], 
    ParentID, 
    IsProject, 
    HLevel 
FROM 
    Hierarchy 
ORDER BY 
    HLevel DESC 
+2

感謝張貼您的解決方案!它節省了我幾個小時! – 2009-11-29 20:35:14