• The correct but bad answer is to start with DECLARE CURSOR and OPEN CURSOR, plus initializing some string variables. Then you enter a loop that uses FETCH to get the next row from the cursor and concatenates the right values to the string variables. After the loop, close and deallocate the cursor, then use EXEC () to execute the dynamic SQL. All the statements mentioned are described in Books Online.

    The much better answer (which you probably do not want to hear, but I am going to give it anyway) is to throw away everything you have and rethink your entire design.

    Using dynamic SQL is a well-known security risk. Google "SQL injection", or read http://www.sommarskog.se/dynamic_sql.html. Every hacker will have standard SQL injection tricks somewhere on the top of things to try. Using sp_executesql instead of EXEC can alleviate the risk, but only if the user-suppllied values are all replaced with parameters. You want table and column names to be dynamic, and they cannot be replaced by parameters - so you will still be vulnerable to injection attacks even if you do use sp_executesql.

    Even worse than the injection risk, is that driving all the logic from a table makes your system completely unmaintainable and untunable.

    If you decide to do go ahead and implement the mess you are planning, then at least make sure that whoever inherits the code will never find out where you live. For they will hate your guts.


    Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)
    Visit my SQL Server blog: https://sqlserverfast.com/blog/
    SQL Server Execution Plan Reference: https://sqlserverfast.com/epr/