根据某个部门ID递归获取其下面所有子部门和本部门信息

方式一:适用SQL2000+

 
  
1 if object_id ( ' sp_GetAllChild ' ) > 0
2   drop proc sp_GetAllChild
3 go
4
5 create proc sp_GetAllChild( @pid varchar ( 20 ))
6 as
7 begin
8 create table #t(ID int ,Parent_ID int ,Name varchar ( 1000 ), level int )
9 declare @t_id varchar ( 1000 ), @l int
10 set @t_id = @pid
11 set @l = 0
12 insert into #t select id,parent_id,name , @l from org_organization where parent_id = @pid or id = @pid
13 while @@rowcount > 0
14 begin
15 set @l = @l + 1
16 insert #t select a.id,a.parent_id,a.name, @l
17 from org_organization a,#t b
18 where a.parent_Id = b.id and b. level = @l - 1
19
20 end
21 select ID,parent_id,name from #t -- where id<>@pid 包括本部门
22
23 end
24
25 -- 测试:exec sp_GetAllChild '13'

方式二:适用SQL2005+

 
  
1 with temp (ID,Parent_ID,Name)
2 as (( select cast (r.ID as integer ) as ID, cast (r.Parent_ID AS integer ),r.Name
3 from Org_Organization r where cast (r.ID as integer ) = 1 )
4 union all ( select cast (cc.ID as integer ), cast (cc.Parent_ID as integer ),cc.Name
5 from Org_Organization cc, temp p where cast (p.ID as integer ) = cast (cc.Parent_ID AS integer ) ))
6 select * from temp where 1 = 1 order by temp .Parent_ID, temp .ID desc

转载于:https://www.cnblogs.com/252e/archive/2011/02/22/1961479.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值