遞歸 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中文網其他相關文章!