actually, you don't even need a while loop and a temp table because select statement itself is already a loop and a dynamic query can do more than what a temp table does. especially when you have a very large size of data, temp table may eat too much resources, and while loop and delete statement also consume extra process time.