您的位置:首页 > 博客中心 > 数据库 >

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

时间:2022-03-14 02:56

  递归格式:

     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

本文出自 “” 博客,请务必保留此出处

热门排行

今日推荐

热门手游