给定以下递归 CTE(对我的示例进行了一些简化):
WITH myCTE (sort, parentid, myid, level, somedata)
AS
(
-- Anchor member definition
SELECT
CAST(ROW_NUMBER() OVER(ORDER BY o.myid) as decimal(38, 20)) as sort,
o.parentid,
o.myid,
0 as level,
o.somedata
FROM
table1 t1,
table2 t1,
datatable o
WHERE t1.somebool = 1 AND t2.id = t1.foreignid and o.foreignkey = t2.key
and o.parentid = ''
UNION ALL
-- Recursive member definition
SELECT
CAST(b.sort + (ROW_NUMBER() OVER(ORDER BY o.myid) / power(10.0, b.level + 1)) as decimal(38, 20)) as sort,
o.parentid,
o.myid,
b.level + 1,
o.somedata
FROM datatable o
INNER JOIN myCTE AS b
ON o.parentid = b.myid
总体思路如下:从基于 table1 和 table2 的项目选择开始,我想启动查询并在锚点中找到所有没有父项的数据,将其与具有主要项目的数据连接起来和父母继续挖掘,直到我找到所有数据。我正在处理一棵深度未知的树,尽管我发现的最高级别是 7。
对递归成员应用额外限制是否有用?我从锚点复制的限制越多,它似乎工作得越好,但仅仅过滤“o.parentid = b.myid”就足够了吗?