作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
鉴于以下递归 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
最佳答案
这是我推荐的调试/调整方法:
1) 添加以下查询提示,排除存在无限循环的可能性。
...
)
SELECT parentid ,
myid ,
[level]
FROM myCTE
OPTION (MAXRECURSION 20)
...
)
SELECT parentid ,
myid ,
[level],
-- I'm not sure what this accomplishes:
-- ROW_NUMBER() OVER (ORDER BY CAST(myid) ASC) / CAST (POWER(10,level) AS DECIMAL(38,20)) AS sort
-- Wouldn't this look nicer?
ROW_NUMBER() OVER (ORDER BY [level] ASC, CAST ([parentid] AS INT) ASC, CAST ([myid] AS INT) ASC) AS sort
FROM myCTE
ORDER BY [sort]
OPTION (MAXRECURSION 20)
关于sql - 如何加速递归 CTE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16810676/
我是一名优秀的程序员,十分优秀!