表T_Sort(id,left,right)
是一个二叉树结构:
a
b c
d e f g
要得到每个节点下的所有节点列表
a:bdecfg
b:de
c:fg
d:
e:
f:
g:
有没有比较高效的查询语句,
先谢过了
--生成测试数据
create table BOM(ID VARCHAR(10),PID VARCHAR(10))
truncate table BOM
insert into BOM select a,NULL
insert into BOM select b,a
insert into BOM select c,a
insert into BOM select d,b
insert into BOM select e,b
insert into BOM select f,c
insert into BOM select g,c
go
--创建用户定义函数
create function f_getChild(@ID VARCHAR(10))
returns varchar(8000)
as
begin
declare @i int,@ret varchar(8000)
declare @t table(ID VARCHAR(10),PID VARCHAR(10),Level INT)
set @i = 1
insert into @t select ID,PID,@i from BOM where PID = @ID
while @@rowcount<>0
begin
set @i = @i + 1
insert into @t
select
a.ID,a.PID,@i
from
BOM a,@t b
where
a.PID=b.ID and b.Level = @i-1
end
select @ret = isnull(@ret,)+ID from @t
return @ret
end
go
--执行查询
select ID,dbo.f_getChild(ID) from BOM group by ID
drop function f_getChild
drop table BOM
你也可以换一下编码方式:
1。编号 名称
01 a
0101 b
0102 c
010101 d
010102 e
......
这样一个节点就可以不止2个孩子了,而且查询得时候会比较方便,不好得地方就是你更新得时候也需要更新相关节点得信息。