项目中经常回遇到表结构存在级联关系的数据结构,如公司的组织架构等。下面是一张常见的表结构:
<code>
create table U_Department
(
DepId int identity(1,1) primary key,
DepName varchar(200) null,
DepPid int null,
DepRemark varchar(500) null
)
</code>
通过<code>with</code>语句可以获得某个<code>DepId</code>下的所有下级部门,以存储过程的形式实现:
<code>
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
</code>
同理,获得某个部门的所有父节点,只需要修改一下<code>where</code>条件和内连接的<code>on</code>条件即可:
<code>
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
</code>
当然,很多其他的方式也可以实现相同的功能,如:游标,表变量等,相比之下,<code>with</code>语句要简洁方便的多。
网友评论