在TSQL腳本中,也能實(shí)現(xiàn)遞歸查詢,SQL Server提供CTE(Common Table Expression),只需要編寫少量的代碼,就能實(shí)現(xiàn)遞歸查詢,本文詳細(xì)介紹CTE遞歸調(diào)用的特性和使用示例,遞歸查詢主要用于層次結(jié)構(gòu)的查詢,從葉級(Leaf Level)向頂層(Root Level)查詢,或從頂層向葉級查詢,或遞歸的路徑(Path)。
一,遞歸查詢原理
CTE的遞歸查詢必須滿足三個(gè)條件:初始條件,遞歸調(diào)用表達(dá)式,終止條件,CTE 遞歸查詢的偽代碼如下:
WITH cte_name ( column_name [,...n] )AS(--Anchor member is definedCTE_query_definition UNION ALL--Recursive member is defined referencing cte_nameCTE_query_definition )-- Statement using the CTESELECT *FROM cte_name
1,遞歸查詢至