取某个部门下的所有子部门SQL语句

数据库部门表如下:
 
departmentid     varchar(20)  部门ID
parentid         varchar(20)  上级部门ID
departmentname   varchar(20)  部门名称
 
现在取某个部门的所有子部门,以及子部门的子部门(递归),从而形成一颗树。
sql语句如下:其中 deptid为某个部门的id
注:如果 deptid为最顶级部门,则该条sql语句形成了部门的整个树结构
 
with temp(departmentid,parentid,departmentname) 
 as ((select cast(r.departmentid as integer) as departmentid,cast(r.parentid AS integer),r.departmentname 
 from sherp.sys_t_department r where cast(r.departmentid as integer)= deptid
 union all (select cast(cc.departmentid as integer),cast(cc.parentid as integer),cc.departmentname 
 from sherp.sys_t_department cc,temp p where cast(p.departmentid as integer) = cast(cc.parentid AS integer) )) 
 select * from temp order by temp.parentid, temp.departmentid desc;
 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值