SQL CTE樹遞歸查詢
阿新 • • 發佈:2017-05-17
.com 分享 com tree nbsp log alt 遞歸查詢 ges 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 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
--樹遞歸查詢,根遍歷子(由外到裏遞歸)
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
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
)
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樹遞歸查詢