1.原始數據結構

2.使用關鍵字:CONNECT BY NOCYCLE
2.1.ERROR:ORA-01436,可使用關鍵字“ NOCYCLE”,自動跳過死循環代碼2.2. SYS_CONNECT_BY_PATH, 可以得到完整的目錄樹
2.3. START WITH: 遞歸開始條件
2.4. CONNECT_BY_ROOT: 指定字段根節點的值
WITH V_ALL AS ( SELECT 'A' AS CODE, 'A1' AS ITEM_CODE FROM DUAL UNION ALL SELECT 'A' AS CODE, 'A2' AS ITEM_CODE FROM DUAL UNION ALL SELECT 'A' AS CODE, 'B' AS ITEM_CODE FROM DUAL UNION ALL SELECT 'B' AS CODE, 'B1' AS ITEM_CODE FROM DUAL UNION ALL SELECT 'B' AS CODE, 'B2' AS ITEM_CODE FROM DUAL UNION ALL SELECT 'B' AS CODE, 'C' AS ITEM_CODE FROM DUAL UNION ALL SELECT 'C' AS CODE, 'D' AS ITEM_CODE FROM DUAL ) SELECT CONNECT_BY_ROOT(A.CODE) AS CODE , A.ITEM_CODE , LEVEL AS NODE_INDEX , REPLACE('0' || SYS_CONNECT_BY_PATH(CODE, '>'), '>' || CODE, '') PARENT_TREE -- 樹形目錄: 上一級層級 , '0' || SYS_CONNECT_BY_PATH(CODE, '>') CURRENT_TREE -- 樹形目錄: 當前層級 , '0' || SYS_CONNECT_BY_PATH(CODE, '>') || '>' || A.ITEM_CODE AS CURRENT_NODE -- 樹形目錄: 完整層級 FROM V_ALL A --START WITH CODE = 'A' CONNECT BY NOCYCLE A.CODE = PRIOR A.ITEM_CODE ORDER BY CODE, CURRENT_NODE ;

3.遞歸函數腳本
3.1.ERROR: ORA-32039: 遞歸 WITH 子句必須具有列別名列表3.1.1.解決方法 - 臨時表后加上別名清單: RESULT(CODE, ITEM_CODE, NODE_INDEX, ROOT_CODE)
WITH V_ALL AS ( SELECT 'A' AS CODE, 'A1' AS ITEM_CODE FROM DUAL UNION ALL SELECT 'A' AS CODE, 'A2' AS ITEM_CODE FROM DUAL UNION ALL SELECT 'A' AS CODE, 'B' AS ITEM_CODE FROM DUAL UNION ALL SELECT 'B' AS CODE, 'B1' AS ITEM_CODE FROM DUAL UNION ALL SELECT 'B' AS CODE, 'B2' AS ITEM_CODE FROM DUAL UNION ALL SELECT 'B' AS CODE, 'C' AS ITEM_CODE FROM DUAL UNION ALL SELECT 'C' AS CODE, 'D' AS ITEM_CODE FROM DUAL ), V_G AS ( SELECT CODE FROM V_ALL GROUP BY CODE ) , RESULT(CODE, ITEM_CODE, NODE_INDEX, ROOT_CODE) as ( SELECT V_G.CODE, V_ALL.ITEM_CODE AS ITEM_CODE, 1 AS NODE_INDEX , V_G.CODE AS ROOT_CODE FROM V_ALL INNER JOIN V_G ON V_G.CODE = V_ALL.CODE UNION ALL SELECT RESULT.CODE, V_ALL.ITEM_CODE, RESULT.NODE_INDEX + 1 AS NODE_INDEX, RESULT.ROOT_CODE FROM V_ALL INNER JOIN RESULT ON RESULT.ITEM_CODE = V_ALL.CODE ) SELECT * FROM result ORDER BY CODE, NODE_INDEX, ITEM_CODE ;
3.2.結果

Reference:
https://www.cnblogs.com/Soprano/p/10659127.htmlhttps://blog.csdn.net/m0_46636892/article/details/122984132
https://blog.csdn.net/wang_yunj/article/details/51040029
connect by 用於存在父子,祖孫,上下級等層級關系的數據表進行層級查詢
oracle遞歸with
https://oracle-base.com/articles/11g/recursive-subquery-factoring-11gr2
