• This is procedural code instead of set-based code. This will work.

    What I mean with this statement is you think in terms of single rows (cursor) instead of a data set of tables (temporary table of statements to execute).
    If you do more database "stuff" feel free to learn the difference. Jeff's articles related to RBAR (also on this site) are the best start. There are others (just want to mention out of this pool the team around Brent Ozar).

    Good for you to have worked it out yourself.