递归 CTE 如何逐行运行?
递归 CTE,就像无尽的 UNION ALL 一样,由一个基本情况和多个递归调用。考虑以下内容:
WITH rows AS ( SELECT * FROM mytable WHERE anchor_condition ), rows2 AS ( SELECT * FROM set_operation(mytable, rows) ), rows3 AS ( SELECT * FROM set_operation(mytable, rows2) ), … SELECT * FROM rows UNION ALL SELECT * FROM rows2 UNION ALL SELECT * FROM rows3 UNION ALL …
在提供的示例中:
WITH abcd1 AS ( SELECT * FROM @tbl t WHERE ParentId IS NULL ), abcd2 AS ( SELECT t.* FROM abcd1 JOIN @tbl t ON t.ParentID = abcd1.id ), abcd3 AS ( SELECT t.* FROM abcd2 JOIN @tbl t ON t.ParentID = abcd2.id ), abcd4 AS ( SELECT t.* FROM abcd3 JOIN @tbl t ON t.ParentID = abcd3.id ), abcd5 AS ( SELECT t.* FROM abcd4 JOIN @tbl t ON t.ParentID = abcd4.id ), abcd6 AS ( SELECT t.* FROM abcd5 JOIN @tbl t ON t.ParentID = abcd5.id ) SELECT * FROM abcd1 UNION ALL SELECT * FROM abcd2 UNION ALL SELECT * FROM abcd3 UNION ALL SELECT * FROM abcd4 UNION ALL SELECT * FROM abcd5 UNION ALL SELECT * FROM abcd6
每个锚点迭代都会产生一个新的递归调用,创建一组嵌套层。锚点被调用一次,作为起点。后续迭代使用先前调用的结果来填充递归成员。
由于 abcd6 没有返回结果,因此意味着停止条件。理论上,递归 CTE 可以是无限的,但 SQL Server 强制执行限制以防止无限记录集。
请参阅以下文章以获取更多见解:
以上是递归CTE如何逐步执行?的详细内容。更多信息请关注PHP中文网其他相关文章!