如何使用游标及递归实现父子部门代码搜索

wbqsln 2007-04-23 03:27:40
初时条件时我有一个table ,里面记录的是几个部门代码
我想找到这几个部门代码所对应的子部门,然后根据找出来的子部门
再去找其子部门(部门层级不清楚,且各部门的子部门不唯一)。
高手们是否有此类功能的现成代码,发出来让寡人研究下,寡人将不胜感激!
...全文
228 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
gahade 2007-04-23
  • 打赏
  • 举报
回复
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')
wbqsln 2007-04-23
  • 打赏
  • 举报
回复
补充一下:我需要把所有找到的部门代码都放到一个table中
然后返回这个table

34,594

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧