您的位置:首页 > 数据库

SQL 递归找查所有子节点及所有父节

2012-11-20 17:46 211 查看
在SQL的树型结构中,很多时候,知道某一节点的值,需要查找该节点的所有子节点(包括多级)的功能,这时就需要用到如下的用户自定义函数.
表结构如下:

IDint
Dep_Typeint
Dep_Codevarchar(50)
Dep_Namevarchar(50)
Dep_Dianint
Dep_FathIDint
Dep_Operavarchar(50)
Dep_Statusint
Dep_AddTimedatetime
用户自定义函数如下:

create function f_getChild(@ID VARCHAR(10))

returns @t table(ID VARCHAR(10),PID VARCHAR(10),Level INT)

as

begin

declare @i int,@ret varchar(8000)

set @i = 1

insert into @t select ID,Dep_FathID,@i from H_Dep_Info where Dep_FathID = @ID

while @@rowcount<>0

begin

set @i = @i + 1

insert into @t select a.ID,a.Dep_FathID,@i from H_Dep_Info a,@t b where a.Dep_FathID=b.ID and b.Level = @i-1

end

return

end

执行操作如下:

select ID from f_getChild(1)

返回值就是所有的子节点

查找父节点的函数如下:

CREATE FUNCTION [f_getParent](@id int)

RETURNS @re TABLE(id int,pid int,level int)

AS

begin

declare @level int

set @level = 1

declare @pid int

select @pid = pid from tb where id = @id

insert @re

select id,pid,@level from tb where id = @pid

while @@rowcount > 0

begin

set @level = @level + 1

select @pid = pid from tb where id = @pid

insert @re

select id,pid,@level from tb where id = @pid

end

return

end

执行操作如下:

select * from f_getParent(8)

返回的列有id,pid,level

其中id就是8的父节点,pid就是id的父节点,level就是级数(表示这个id是8的第几级你节点)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: