I recently came across a T-SQL procedure which is developed to take a backup of table in separate database (i.e. Trash ) with 'xxx_TableName_YYYYMMDD' format. Since the proc keeps on adding tables every time it gets executes, I was asked to improve it to not to keep more than 5 table in the trash database. The following code resolve that issue.
This code shows how to execute a result of a dynamic query (@SQL1) in another dynamic query (@SQL3) using SP_EXECUTESQL system procedure.