34,875
社区成员
发帖
与我相关
我的任务
分享create table tb (id int,pid int,lvl int)
insert into tb values(1,0,0)
insert into tb values(2,0,0)
insert into tb values(3,0,0)
insert into tb values(4,2,1)
insert into tb values(5,2,2)
insert into tb values(6,2,3)
insert into tb values(7,3,1)
go
create function f_tree(@id int) returns varchar(1000)
as
begin
declare @ret varchar(1000) , @pid int
set @ret = rtrim(@id)
while exists(select 1 from tb where id = @id and pid <> 0 )
begin
select @pid = pid from tb where id = @id and pid <> 0
set @id = @pid
set @ret = rtrim(@id)+ @ret
end
return @ret
end
go
select * from tb order by dbo.f_tree(id)
/*
id pid lvl
----------- ----------- -----------
1 0 0
2 0 0
4 2 1
5 2 2
6 2 3
3 0 0
7 3 1
(所影响的行数为 7 行)
*/
drop function f_tree
drop table tb
create table tb (id int,pid int,lvl int)
insert into tb values(1,0,0)
insert into tb values(2,0,0)
insert into tb values(3,0,0)
insert into tb values(4,2,1)
insert into tb values(5,2,2)
insert into tb values(6,2,3)
insert into tb values(7,3,1)
go
;with t as
(
select *,px=cast(id as varbinary(max)) from tb
where [pid]=0
union all
select a.*,px+cast(a.id as varbinary)
from tb a
join t b on a.[pid]=b.id
)
select id,[pid],lvl
from t
order by px
drop table tb
/*
id pid lvl
----------- ----------- -----------
1 0 0
2 0 0
4 2 1
5 2 2
6 2 3
3 0 0
7 3 1
(7 行受影响)
*/
declare @t table (id int,pid int,lvl int);
insert into @t values(1,0,0),(2,0,0),(3,0,0),
(4,2,1),(5,2,2),(6,2,3),(7,3,1),(8,4,1),(9,4,2),(10,3,2);
with t as (
select id,pid,lvl,cast(right('000'+ltrim(id),4) as varchar(100)) [path] from @t where pid=0
union all
select r.id,r.pid,r.lvl,
cast([path]+','+right('000'+ltrim(r.id),4) as varchar(100))
from @t r, t where t.id=r.pid
)
select id,pid,lvl from t order by [path],lvl;
/*
1 0 0
2 0 0
4 2 1
8 4 1
9 4 2
5 2 2
6 2 3
3 0 0
7 3 1
10 3 2
*/
select * from tb order by case when pid!=0 then pid else id end,level