SqlServerl递归的一种实现——with as

项目中经常回遇到表结构存在级联关系的数据结构,如公司的组织架构等。下面是一张常见的表结构:

create table U_Department
(
DepId int identity(1,1) primary key,
DepName varchar(200) null,
DepPid int null,
DepRemark varchar(500) null
)

通过with语句可以获得某个DepId下的所有下级部门,以存储过程的形式实现:

create procedure P_GetChildrenOfDepartment(@DepId int)
as
begin
with Dep as
(
select DepId,DepPid
from U_Department
where DepPid=@DepId
union all
select DepId,DepPid
from U_Department d inner join Dep p on d.DepPid=p.DepId
)
select DepId from Dep
end

同理,获得某个部门的所有父节点,只需要修改一下where条件和内连接的on条件即可:

create procedure P_GetParentOfDepartment(@DepId int)
as
begin
with Dep as
(
select DepId,DepPid
from U_Department
where DepId=@DepPid
union all
select DepId,DepPid
from U_Department d inner join Dep p on d.DepId=p.DepPid
)
select DepId from Dep
end

当然,很多其他的方式也可以实现相同的功能,如:游标,表变量等,相比之下,with语句要简洁方便的多。

你可能感兴趣的:(SqlServerl递归的一种实现——with as)