Search code examples
t-sqlsql-server-2014

Recursive CTE never finishes


This recursive CTE runs forever (never returns results), when obtaining the same results by hand would take about 10 seconds, with most of that being copy-pasting.

  • Did I misimplement the RekeyLevel part? Is it not leveling up appropriately?
  • How would I make it so the recursion stops when no results are found, rather than needing a failsafe like RekeyLevel <= 2?

Current query:

with RekeysAllLevelsDeep as (

select
 a.claimid as Rekey
,a.ClaimIDAdjFromOrig as Original
,0 as RekeyLevel

from <base table> (nolock) a

where a.ClaimIDAdjFromOrig is not null
    and a.ClaimIDAdjFromOrig <> a.ClaimID


union all


select
 a.claimid as Rekey
,a.ClaimIDAdjFromOrig as Original
,RekeyLevel + 1

from RekeysAllLevelsDeep

join <base table> (nolock) a
    on RekeysAllLevelsDeep.Original = a.ClaimID

where a.ClaimIDAdjFromOrig is not null
    and a.ClaimIDAdjFromOrig <> a.ClaimID
    and RekeyLevel <= 2
)

select distinct
 Rekey
,Original
,RekeyLevel

from RekeysAllLevelsDeep

where Original is not null
    and Original <> Rekey
    and Rekey = '(<number>)'

Solution

  • I needed to move the condition I used outside the recursive CTE, and Rekey = '(<number>)', inside of it. Doing so made the recursive CTE return correct results immediately. Having the condition outside the recursive CTE meant that the recursive CTE was doing this recursion for every number in the entire table.