CTE - 递归查询做得太多了

时间:2016-06-03 11:01:32

标签: sql sql-server recursion common-table-expression

我有当前的数据表......

| LoanRollupID | NewLoanID | PreviousLoanID |
|--------------|-----------|----------------|
| 11           | 76        | 44             |
| 12           | 80        | 75             |
| 13           | 83        | 82             |
| 14           | 84        | 83             |
| 15           | 86        | 85             |
| 16           | 87        | 54             |
| 17           | 88        | 87             |
| 18           | 90        | 48             |
| 19           | 91        | 34             |
| 20           | 93        | 41             |
| 21           | 94        | 76             |
| 22           | 95        | 90             |
| 23           | 96        | 94             |
| 24           | 100       | 92             |
| 25           | 101       | 99             |
| 26           | 102       | 98             |
| 27           | 103       | 101            |
| 28           | 104       | 81             |
| 29           | 105       | 80             |
| 30           | 107       | 52             |
| 31           | 110       | 108            |
| 1029         | 1105      | 103            |
| 1030         | 1106      | 104            |
| 1031         | 1108      | 1106           |
| 1032         | 1109      | 73             |

我正试图进入NewLoanID 1108,看看它是如何从以前的贷款演变而来的。例如1108来自1106,来自104,来自81,等等。

当我运行此查询时:

WITH OldLoans (PreviousLoanID, NewLoanID, start)
AS
(
---- Anchor member definition
SELECT l.NewLoanID, l.PreviousLoanID, 0 as start
FROM dscs_public.LoanRollup l
Where NewLoanID = 1108
UNION ALL
-- Recursive member definition
SELECT l.NewLoanID, l.PreviousLoanID, start + 1
FROM dscs_public.LoanRollup l
INNER JOIN OldLoans AS o
    ON o.NewLoanID = l.PreviousLoanID
)
---- Statement that executes the CTE
SELECT PreviousLoanID, NewLoanID, start
FROM OldLoans

失败并出现此错误:

  

声明终止。最大递归100已经用尽   在声明完成之前。

有人能发现我的错误吗? 感谢。

1 个答案:

答案 0 :(得分:2)

CTE定义中的别名顺序错误:

-- Instead of (PreviousLoanID, NewLoanID, start)
WITH OldLoans (NewLoanID, PreviousLoanID, start)
AS
(
   ---- Anchor member definition
   SELECT l.NewLoanID, l.PreviousLoanID, 0 as start
   FROM mytable l --LoanRollup l
   Where NewLoanID = 1108

   UNION ALL

   -- Recursive member definition
   SELECT l.NewLoanID, l.PreviousLoanID, start + 1
   FROM mytable l --dscs_public.LoanRollup l
   INNER JOIN OldLoans AS o
       -- Instead of o.NewLoanID = l.PreviousLoanID
       ON l.NewLoanID = o.PreviousLoanID

)
---- Statement that executes the CTE
SELECT PreviousLoanID, NewLoanID, start
FROM OldLoans

同样适用于递归成员定义中的ON子句。