• Note that COMMIT statement will not execute if there is no data in @TableToBeCleaned satisfying the where clause.

    Change the fourth line as

    SET @STR = @STR + 'COMMIT ' + 'IF @@ROWCOUNT = 0 ' + 'BREAK ' + 'END ' + 'SET ROWCOUNT 0'