Would this not benefit from using a tally table? It would save the loops and missing IDs could be simply omitted?
Not a Tally Table, per se` but a Tally-Like structure using ROW_NUMBER() OVER, and that's already been suggested.
--Jeff Moden
RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row. First step towards the paradigm shift of writing Set Based code: ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.
Change is inevitable... Change for the better is not.