sql 使用with 递归

 ---前提:有上下级关系的关系表
 ---示例:组织架构表
DECLARE @orgId NVARCHAR(20)='0001';
--向下递归,查询@orgId 下的所有结点。。。包括儿子-孙子节点-到最后的叶子节点
WITH cte
AS
(
SELECT * ,0 AS level FROM dbo.Organization WHERE OrgId=@orgId
UNION ALL
SELECT g.*,level+1 FROM dbo.Organization g INNER JOIN cte
ON g.ParentOrgId=cte.orgId
)
SELECT * FROM cte
 
 
--向上递归,查询@orgId 往上,一直到最根节点
WITH cte
AS
(
SELECT * FROM dbo.Organization WHERE OrgId=@orgId
UNION ALL
SELECT g.* FROM dbo.Organization g INNER JOIN cte
ON g.OrgId=cte.ParentOrgId
)
SELECT * FROM cte
 
posted @ 2022-05-31 15:33  周捷Jay  阅读(112)  评论(0编辑  收藏  举报