4te3r3r 发表于 2014-11-25 09:44:20

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

递归格式:
   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
页: [1]
查看完整版本: SqlServer 递归与函数的结合获取部门集合