SQL CTE树递归查询

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL CTE树递归查询相关的知识,希望对你有一定的参考价值。

--树递归查询,根遍历子(由外到里递归)
WITH MenuTree 
AS
(
SELECT * FROM dbo.HR_SYS_Menu WHERE UpCode = 5
UNION ALL
SELECT dbo.HR_SYS_Menu.* FROM MenuTree
JOIN dbo.HR_SYS_Menu ON MenuTree.ID = dbo.HR_SYS_Menu.UpCode
)
SELECT * FROM MenuTree
GO

--树递归查询,子遍历根(由里到外递归)
WITH MenuTree 
AS
(
SELECT * FROM dbo.HR_SYS_Menu WHERE ID = 521
UNION ALL
SELECT dbo.HR_SYS_Menu.* FROM MenuTree
JOIN dbo.HR_SYS_Menu ON MenuTree.UpCode = dbo.HR_SYS_Menu.ID
)
SELECT * FROM MenuTree

技术分享


--树递归查询,子遍历根(由里到外递归)
WITH MenuTree
AS
(
SELECT A.ID,A.UpCode,A.Name FROM dbo.HR_SYS_Menu A WHERE ID = 521
UNION ALL
SELECT dbo.HR_SYS_Menu.ID,dbo.HR_SYS_Menu.UpCode,dbo.HR_SYS_Menu.Name FROM MenuTree B
JOIN dbo.HR_SYS_Menu ON B.UpCode = dbo.HR_SYS_Menu.ID
)
SELECT * FROM MenuTree
GO
--树递归查询,根遍历子(由外到里递归)
WITH MenuTree
AS
(
SELECT A.ID,A.UpCode,A.Name FROM dbo.HR_SYS_Menu A WHERE A.UpCode = 5
UNION ALL
SELECT dbo.HR_SYS_Menu.ID,dbo.HR_SYS_Menu.UpCode,dbo.HR_SYS_Menu.Name FROM MenuTree B
JOIN dbo.HR_SYS_Menu ON B.ID = dbo.HR_SYS_Menu.UpCode
)
SELECT * FROM MenuTree
GO

技术分享

以上是关于SQL CTE树递归查询的主要内容,如果未能解决你的问题,请参考以下文章

SQL 递归查询,意淫CTE递归的执行步骤

MYSQL 8.019 CTE 递归查询怎么解决死循环三种方法

Presto SQL 是不是像 SQL Server 一样支持使用 CTE 进行递归查询?例如员工等级

sql server使用cte递归查询获取树形的父节点/子节点

SQL With (递归CTE查询)

sql递归cte在视图中不能正常工作