看起来您的 CTE 是错误的 - 您快到了,但递归成员定义位看起来错误。
尝试:
SELECT * FROM pg_Pages;
WITH RecursiveTable (PageId, PageInheritance, Level)
AS
(
--Anchor
SELECT tt.PageId, tt.PageInheritance, 0 AS Level
FROM pg_Pages AS tt
WHERE PageInheritance = 0
UNION ALL
--Recursive member definition
SELECT tt.PageId, tt.PageInheritance, Level + 1
FROM pg_Pages AS tt
INNER JOIN RecursiveTable rt ON
tt.PageInheritance = rt.PageId
)
SELECT *
FROM RecursiveTable
--SELECT * FROM RecursiveTable WHERE Level = 0
在您最初的尝试中,您的 pg_Pages 别名必须是 tt (并且您还需要在 PageInheritance 前面加上 tt 前缀)。
否则,它看起来很好。
编辑
对于您的其他问题,您只需添加其他列:
SELECT * FROM pg_Pages;
WITH RecursiveTable (PageId, PageName, PageInternalLink, PageInternalLinkUrl, PageInheritance, Level)
AS
(
--Anchor
SELECT tt.PageId, tt.PageName, tt.PageInternalLink, tt.PageInternalLinkUrl, tt.PageInheritance, 0 AS Level
FROM pg_Pages AS tt
WHERE PageInheritance = 0
UNION ALL
--Recursive member definition
SELECT tt.PageId, tt.PageName, tt.PageInternalLink, tt.PageInternalLinkUrl, tt.PageInheritance, Level + 1
FROM pg_Pages AS tt
INNER JOIN RecursiveTable rt ON
tt.PageInheritance = rt.PageId
)
SELECT *
FROM RecursiveTable
--SELECT * FROM RecursiveTable WHERE Level = 0
进一步编辑:
好的,做你想做的,你可以把查询转过来;如果您知道页面 ID:
DECLARE @PageId int
SET @PageId = 39;
WITH RecursiveTable (PageId, PageName, PageInternalLink, PageInternalLinkUrl, PageInheritance, Level)
AS(
--Anchor
SELECT tt.PageId, tt.PageName, tt.PageInternalLink, tt.PageInternalLinkUrl, tt.PageInheritance, 0 AS Level
FROM TestPage AS tt
WHERE PageId = @PageId
UNION ALL
--Recursion
SELECT tt.PageId, tt.PageName, tt.PageInternalLink, tt.PageInternalLinkUrl, tt.PageInheritance, Level + 1
FROM TestPage AS tt
INNER JOIN RecursiveTable rt ON rt.PageInheritance = tt.PageId
)
SELECT * FROM RecursiveTable ORDER BY Level DESC
我们在这里所做的是从您所在的页面开始,然后通过表格向后工作以寻找所有父母。在这种情况下,级别最高的记录是最终父项,因此我们按降序逐级排序以反映这一点。