• If you're getting this sophisticated with dynamic SQL, then you really need to look into sp_executesql instead of simply using the exec statement. sp_executesql will allow you to define parameters within your dynamic sql, which means it will create execution plans that are more likely to be reused rather than a new compile each and every time. It works largely like exec, but not entirely. Look it up in the Books Online.

    "The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood"
    - Theodore Roosevelt

    Author of:
    SQL Server Execution Plans
    SQL Server Query Performance Tuning