码迷,mamicode.com
首页 > 数据库 > 详细

SQL CTE树递归查询

时间:2017-05-17 22:17:00      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:http   遍历   sys   --   nio   where   alt   技术分享   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树递归查询

标签:http   遍历   sys   --   nio   where   alt   技术分享   cte   

原文地址:http://www.cnblogs.com/linhongquan/p/6869597.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!