无限循环父子树(主要是数据库里面的一张表,然后根据ID查找父类的名称,以及查找子类的名称) 自己思考,存点东西。...

本文介绍了一种使用SQL实现父子树结构的方法,并提供了查询特定节点及其父节点名称、查询特定父节点下所有子节点名称的功能实现。通过函数和存储过程的方式,展示了如何递归地获取树形结构中节点之间的关系。

 

代码
--无限循环父子树
create table Father(Fid int identity(1,1),Fname nvarchar(20),FatherId int)
insert into Father
select '数据库开发',0 union all
select 'MS-SQL SERVER',1 union all
select '基础类',1 union all
select '应用实例',1 union all
select 'BI',1 union all
select 'BISS',5 union all
select 'BIAA',6 union all
select 'Oracle',0 union all
select 'VFP',8 union all
select 'Access',8 union all
select 'Sybase',8 union all
select 'MySql',8 union all
select 'MySqlss',12
select * from Father
/*
Fid Fname FatherId
----------- -------------------- -----------
1 数据库开发 0
2 MS-SQL SERVER 1
3 基础类 1
4 应用实例 1
5 BI 1
6 BISS 5
7 BIAA 6
8 Oracle 0
9 VFP 8
10 Access 8
11 Sybase 8
12 MySql 8
13 MySqlss 12
*/
select * from Father where FatherId=0
/*
Fid Fname FatherId
----------- -------------------- -----------
1 数据库开发 0
8 Oracle 0
*/
-- 一、知道子类ID找父类名称
--
1、函数
alter function f_getParent(@fid int)
returns varchar(40)
as
begin
declare @ret varchar(40)

while exists(select 1 from Father where Fid=@fid and FatherId<>0)
begin
select @fid=b.Fid,@ret=','+rtrim(b.Fname)+isnull(@ret,'')
from
Father a,Father b
where
a.Fid
=@fid and b.Fid=a.FatherId
end

set @ret=stuff(@ret,1,1,'')
return @ret
end
go
select Fid,isnull(dbo.f_getParent(Fid),'根目录') as Fname from Father
/*
Fid Fname
----------- ------------------
1 根目录
2 数据库开发
3 数据库开发
4 数据库开发
5 数据库开发
6 数据库开发,BI
7 数据库开发,BI,BISS
8 根目录
9 Oracle
10 Oracle
11 Oracle
12 Oracle
13 Oracle,MySql
*/
--2、存储过程
alter procedure f_getParents
@fid int,
@parent nvarchar(100) out
as
begin

while exists(select 1 from Father where Fid=@fid and FatherId<>0)
begin
select @fid=b.Fid,@parent=','+rtrim(b.Fname)+isnull(@parent,'')
from
Father a,Father b
where
a.Fid
=@fid and b.Fid=a.FatherId
end

set @parent=stuff(@parent,1,1,'')
select @parent
end
go
exec f_getParents 13,''--查MySqlss父目录的名称
/*

--------------------------
Oracle,MySql
*/

-- 二、知道父类ID找所属子类名称
alter procedure f_getSons
@FatherId int,
@sons nvarchar(100) out
as
begin
while exists(select 1 from Father where FatherId=@FatherId)
begin
select @FatherId=b.Fid,@sons=','+rtrim(b.Fname)+isnull(@sons,'')
from
Father a,Father b
where a.Fid=@FatherId and b.FatherId=a.Fid
end
set @sons=stuff(@sons,1,1,'')
set @sons=isnull(@sons,'无子类')
select @sons
end
go

exec f_getSons 1,''
/*
-----------------------------------------
BIAA,BISS,BI,应用实例,基础类,MS-SQL SERVER
*/

 

转载于:https://www.cnblogs.com/sibiyellow/archive/2010/10/08/1846018.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值