• It's a bit harder with variables not defined, no test data, no DDL, etc but as a guess:
    It looks like you set @r to 1 and it never changes but you probably didn't mean to do that.
    Your Inner While loop that you're building in the @sqlrun is while 1 > 0 and it is always that since @r never changes.
    In your @sqlrun string you are doing SET 1 = @@rowcount. I would guess you instead wanted SET @r = @@rowcount with something like:

    'SET @r ' + '='+ CAST (@@ROWCOUNT AS VARCHAR(10)) + CHAR(13) +

    For the error, I would guess you ended up with a SET 1 = 1 to get that error.

    Sue