递归格式:
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