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