Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

sql - CTE to traverse back up a hierarchy?

I can find all the children of a given record in a hierarchical data model (see code below) but I'm not sure how to traverse back up the Parent/Child chain with a given Child ID. Can anyone point me in the right direction to figure out how to do this? Is this possible in Linq to SQL as well?

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]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ah, I figured it out:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...