您的位置:首页 > 数据库

SQL_存储过程——获得一棵树的所有叶子节点

2015-06-24 15:31 141 查看


数据在数据库中的存储结构简化为:

A B1

A B2

B1 C1

B1 C2

B2 C3

B2 C4……

存储过程的代码如下:

CREATE PROCEDURE usp_test_GetLeavesOfTree
(
@Parent nvarchar(255),
@SR varchar(20)
)
AS
BEGIN

declare @count int
set @count=4
declare @ResultTable table(Terms nvarchar(255))
declare @TemTable table(Terms nvarchar(255))

insert  @ResultTable
select @Parent

while @count>0
begin
delete from @TemTable
insert @TemTable
select b.Term from Semantics,Glossary a,Glossary b,@ResultTable c
where a.Term=c.Terms
and a.Id=Semantics.T1
and b.Id=Semantics.T2
and SR=@SR
union
select c.Terms from @ResultTable c
where not exists(select a.Term from Semantics,Glossary a where a.Id=Semantics.T1 and a.Term=c.Terms and SR=@SR)
delete from @ResultTable
insert into @ResultTable select* from @TemTable
set @count=@count-1
end
select *  from  @ResultTable order by Terms
END


整体的思路为:根据根节点找到子节点,子节点找子子节点,其中要判断上一级节点是否为叶子节点如果是则添加到结果表中。叶子节点的特点就是只出现在第二列中,第一列中不存在。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: