• I found your loop and CTE are not equivalent. In the loop, you have the code

    WHERE ...

    and c2.structureid not in

    (select structureid

    from @hierarchy)

    which slows it down.