oracle中的CTE循环错误

时间:2014-05-21 12:10:40

标签: sql oracle common-table-expression

http://sqlfiddle.com/#!4/5f3b40/1

我有一张表del

 CMPI_CODE CMPI_ID_REF
---------- -----------
        51             
        52          51 
        53             
        54             
        55             
        56             
        57             
        58             
        59             
        60             
        61             
        62             
        81             
        82          61 
        83             
        84             

-

WITH RSFC(A,B,LVL) AS 
  (SELECT CMPI_CODE,CMPI_ID_REF,0 AS LVL FROM del R where CMPI_ID_REF is null
  UNION ALL SELECT A,B,LVL+1 FROM RSFC R
  INNER JOIN DEL F ON R.A = F.CMPI_ID_REF
  ) 
  select * from rsfc 

这就像显示错误SQL Error: ORA-32044: cycle detected while executing recursive WITH query

2 个答案:

答案 0 :(得分:1)

您似乎在递归成员中选择了错误的值。仅查看前两行,锚成员将A, B, LVL作为51, null, 0。第一个递归成员将使用51来获取第二行;但是你选择了A, B, LVL+1,这样就会得到51, null, 1。然后下一个会得到相同的...因此循环。所以你需要选择:

  UNION ALL SELECT F.CMPI_CODE,CMPI_ID_REF,LVL+1 FROM RSFC R
  INNER JOIN DEL F ON R.A = F.CMPI_ID_REF

SQL Fiddle基于你的。不确定这是否是您想要的最终结果。

答案 1 :(得分:0)

Oracle不使用与Sql server相同的语法进行分层查询,而WITH关键字则用于不同的用途。

进行分层查询使用以下查询:

SELECT DEL.*, level as LVL
FROM
    DEL 
CONNECT BY PRIOR
    CMPI_CODE = CMPI_ID_REF
START WITH
    CMPI_ID_REF IS NULL;