您可以在执行递归时构建一个列进行排序。
像这样的东西:
declare @t table
(
ID int,
ParentID int,
Name varchar(10)
);
insert into @T values
(1, null, 'team1'),
(2, null, 'team2'),
(3, null, 'team3'),
(4, 1, 'team1-1'),
(5, 1, 'team1-2'),
(6, 3, 'team3-1');
with C as
(
select T.ID,
T.ParentID,
T.Name,
cast(right(100000 + row_number() over(order by T.ID), 5) as varchar(max)) as Sort
from @T as T
where T.ParentID is null
union all
select T.ID,
T.ParentID,
T.Name,
C.Sort+right(100000 + row_number() over(order by T.ID), 5)
from @T as T
inner join C
on T.ParentID = C.ID
)
select *
from C
order by Sort
结果:
ID ParentID Name Sort
----------- ----------- ---------- ------------
1 NULL team1 00001
4 1 team1-1 0000100001
5 1 team1-2 0000100002
2 NULL team2 00002
3 NULL team3 00003
6 3 team3-1 0000300001