加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

SqlServer 递归与函数的结合获取部门集合

发布时间:2020-12-12 12:40:53 所属栏目:MsSql教程 来源:网络整理
导读:? 递归格式: ????? WITH CTE名称(字段列表)? ? ???????AS? ? ? ? ? ?(? ? ? ? ? ? ? ? ? 查询语句? ? ? ? ? ? )? ? 获取当前部门的所有下级部门语句: ????????create function GetchildrenDepartments(@currentdepartid int) ????????returns table ??????

? 递归格式:

?????WITH CTE名称(字段列表)?
? ???????AS?
? ? ? ? ?(?
? ? ? ? ? ? ? ? 查询语句?
? ? ? ? ? )?

? 获取当前部门的所有下级部门语句:

????????create function GetchildrenDepartments(@currentdepartid int)

????????returns table

????????as

????????????return

????????????????????with cte(id,mainid)

????????????????????as

????????????????????(select id,mainid from u_department where id=@currentdepartid

????????????????????? union all

????????????????????? select a.id,a.mainid from u_department a inner join cte b on a.mainid=b.id

????????????????????)

????????????????????select * from cte

? 特别注意:

????如果想获取当前部门的所有上级部门集合:红色部分应该替换成 a.id=b.mainid

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读