What I see in your question is encapsulation:
- with dynamic SQL expression
- execute it to populate a parameterized table
Why do you want to have such encapsulation?
First of all, this can adversely affect the performance of your database. Read this in EXEC () and sp_executesql () . I hope that your SP will not be called from several parts of your application, because it will lead to trouble, at least to performance.
Another thing is how and where do you build your SQL? Obviously, you are doing this somewhere else, and it seems that it was created manually. If we are talking about a modern application, there are many OR / M solutions for this, and whenever possible you should always avoid manually assembling TSQL at run time. Not to mention that EXEC does not protect you from any form of SQL injection attack. However, if all of this is part of the TSQL database administration package, forget its paragraph.
In the end, if you just want to load a new table from any existing table (or part of it) as part of some administration task in TSQL, consider releasing SELECT ... INTO ... This will create a new target table structure for you ( excluding indexes and restrictions) and copy the data. SELECT INTO will outperform INSERT INTO SELECT because SELECT INTO will be minimally registered .
Hope this gets you (and others) at least a little on the right track.
source share