当前位置:  开发笔记 > 编程语言 > 正文

CTE遍历层次结构?

如何解决《CTE遍历层次结构?》经验,为你挑选了1个好方法。



1> RichC..:

啊,我弄清楚了:

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


感谢您发布解决方案!它节省了我几个小时!
推荐阅读
可爱的天使keven_464
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有