You can build a column to sort by when you do the recursion.
Something like this:
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
Result:
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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…