select a.id,REPLICATE('-',a.depth)+a.name from test0112 a
left join test0112 b
on a.parentID=b.id
left join test0112 c
on b.parentID=c.id
left join test0112 d
on c.parentID=d.id
left join test0112 e
on b.parentID=e.id
order by
isnull(e.[index],isnull(d.[index],isnull(c.[index],isnull(b.[index],isnull(a.[index],0)))))
create table test0112(
ID int,
parentID int,
depth int,
name varchar(100),
[index] int
)
go
insert test0112
select
1,0,1,'a1',1
union all
select
2,1,2,'a11',1
union all
select
3,1,2,'a12',2
union all
select
4,0,1,'b2',2
union all
select
5,4,2,'b21',1
union all
select
6,3,3,'a121',1
go
create function C1000(@depth int)
returns bigint
as
begin
declare @r bigint
declare @i int
set @i=@depth
set @r=1
while @i>0
begin
set @r=@r*1000
set @i=@i-1
end
return @r
end
go
create function GetIndex(@Id int)
returns bigint
as
begin
declare @r bigint
declare @parentID int
declare @depth int
declare @Index int
declare @Maxdepth int
declare @i int
select @Maxdepth=max(depth) from test0112
select @parentID=parentID,@depth=@Maxdepth-depth,@Index=[Index] from test0112 where id=@id
if isnull(@parentID,0)=0
set @r=dbo.C1000(@depth)*@Index
else
set @r=dbo.C1000(@depth)*@Index+dbo.GetIndex(@parentID)
return @r
end
go
调用:
select id,REPLICATE('-',depth)+name from test0112
order by dbo.GetIndex(id)
INSERT INTO #aa VALUES(0,1,'层1',1)
INSERT INTO #aa VALUES(1,2,'层11',1)
INSERT INTO #aa VALUES(1,2,'层12',2)
INSERT INTO #aa VALUES(0,1,'层2',1)
INSERT INTO #aa VALUES(4,2,'层21',1)
select ID,LEFT('----------------',depth)+[name] from #aa
ORDER BY LEFT(name,2),[index]