数据表的遍历(急等,加分)

刚刚得到一个案例,在数据库中实现二叉树的遍历.
我的表结构如下:
ID LeftID RightID
1 2 3
2 4 5
3 6 NULL
4 NULL NULL
5 NULL NULL
6 NULL NULL
如何从一个节点开始分别实现左子树和右子树的遍历?

---------------------------------------------------------------

--生成测试数据
Create table BOM(ID int,LeftID int,RightID int)
insert into BOM select 1,2 ,3
insert into BOM select 2,4 ,5
insert into BOM select 3,6 ,NULL
insert into BOM select 4,NULL,NULL
insert into BOM select 5,NULL,NULL
insert into BOM select 6,NULL,NULL
GO

--创建用户定义函数
create function f_getChild(@ID int,@Type int)
returns @t table(ID INT,LeftID INT,RightID INT,Level INT)
as
begin
declare @i int
set @i = 1

insert into @t
select
ID,
(case @Type when 1 then LeftID end),
(case @Type when 2 then RightID end),
@i
from
BOM where ID = @ID

while @@rowcount<>0
begin
set @i = @i + 1

insert into @t
select
a.ID,a.LeftID,a.RightID,@i
from
BOM a,@t b
where
(a.ID=b.LeftID or a.ID=b.RightID) and b.Level = @i-1
end

return
end
go

--执行查询
select ID from dbo.f_getChild(1,1) where ID != 1
--输出结果
/*
ID
----
2
4
5
*/

select ID from dbo.f_getChild(1,2) where ID != 1
--输出结果
/*
ID
----
3
6
*/

--删除测试数据
DROP FUNCTION f_getChild
DROP TABLE BOM
GO
---------------------------------------------------------------

--生成测试数据
Create table BOM(ID int,pid int,flag int) --id自身编号,pid父编号,flag:标志是左还是右
insert into BOM select 1,0,0
insert into BOM select 2,1,0 --0:是左,1:是右
insert into BOM select 3,1,1
insert into BOM select 4,2,0
insert into BOM select 5,2,1
insert into BOM select 6,3,0
insert into BOM select 7,6,0
GO

--创建用户定义函数
create function f_getChild(@ID int,@Type int) --@type:0是左,1:是右.
returns @t table(ID int,pid int,flag int,Level INT)
as
begin
declare @i int
set @i = 1

insert into @t
select ID,pid,flag,@i from BOM where ID = @ID

while @@rowcount<>0
begin
set @i = @i + 1

insert into @t
select a.ID,a.pid,a.flag,@i
from
BOM a,@t b
where
a.pid=b.id and (a.flag=@type and @i=2 or @i>2) and b.Level = @i-1
end

return
end
go

--执行查询
select ID from dbo.f_getChild(1,0)
--输出结果
/*
ID
----
1
2
4
5
*/

select ID from dbo.f_getChild(1,1)
--输出结果
/*
ID
----
3
6
*/

--删除测试数据
DROP FUNCTION f_getChild
DROP TABLE BOM
GO

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus