Ordering hierarchy from recursive query results in SQL 2005

后端 未结 4 628
星月不相逢
星月不相逢 2020-12-16 06:36

I\'ve got a \'Task\' table with the following columns (the TaskOrder is for ordering the children within the scope of the parent, not the entire table):

TaskId
Pa         


        
4条回答
  •  孤街浪徒
    2020-12-16 07:26

    One way you could do this is to add a hierarchy column that has all previous IDs in a list:

    with tasks (TaskId, ParentTaskId, [Name], TaskIdList) as
    (
        select parentTasks.TaskId,
               parentTasks.ParentTaskId,
               parentTasks.[Name],
               parentTasks.TaskId
        from   Task parentTasks
        where  ParentTaskId is null
    
        union all
    
        select childTasks.TaskId,
               childTasks.ParentTaskId,
               childTasks.[Name],
               tasks.TaskIdList + '.' + childTasks.TaskId
        from   Task childTasks
        join   tasks
        on     childTasks.ParentTaskId = tasks.TaskId
    )
    
    select TaskId, ParentTaskId, [Name] from tasks
       order by TaskIdList
    

    Note that this assumes that TaskId is a string-based ID. If not, you should cast it to a varchar before concatenating it.

提交回复
热议问题