项目中经常回遇到表结构存在级联关系的数据结构,如公司的组织架构等。下面是一张常见的表结构:
<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>语句要简洁方便的多。
SqlServerl递归的一种实现——with as
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 什么是SQL数据库: SQL是Structured Query Language(结构化查询语言)的缩写。SQL是...