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.
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>)'
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.