日期:2014-05-19  浏览次数:20433 次

如何使用游标及递归实现父子部门代码搜索
初时条件时我有一个table   ,里面记录的是几个部门代码
我想找到这几个部门代码所对应的子部门,然后根据找出来的子部门
再去找其子部门(部门层级不清楚,且各部门的子部门不唯一)。
高手们是否有此类功能的现成代码,发出来让寡人研究下,寡人将不胜感激!

------解决方案--------------------
create table t_1(code varchar(10),parent varchar(10))
insert into t_1(code,parent)
select 'A ', '0 '
union all select 'E ', 'A '
union all select 'E01 ', 'E '
union all select 'E02 ', 'E '

create table t_2(code varchar(10),value int)
insert into t_2(code,value)
select 'E01 ',3
union all select 'E02 ',4

--递归取下级
create function f_getchild(@code varchar(10))
returns @t table(code varchar(10))
as
begin
declare @t_temp table(id int identity(1,1),child varchar(10))
insert into @t(code)
select code from t_1 where Parent = @code

insert into @t_temp(child)
select code from t_1 where Parent = @code

declare @child_temp varchar(10),@max_id int,@min_id int
select @max_id = max(id),@min_id = min(id) from @t_temp
while @min_id <= @max_id
begin
select @child_temp = child from @t_temp where id = @min_id
insert into @t(code)
select * from dbo.f_getchild(@child_temp)
select @min_id = @min_id + 1
end
return
end
--调用
select code from dbo.f_getchild( 'E01 ')