I have a procedure that builds out a dynamic SQL query simplified as
@mySQLQuery = 'SELECT ' + @myCol + 'FROM' + @myTable
I would like to select this query into a temp table to be used later in my procedure, but I can't figure out the right syntax.
SELECT * INTO #myTempTable FROM ( @mySQLQuery) x
is basically what I want to do.
I tried sp_executeSQL 'SELECT * INTO #myTempTable FROM (' + @mySQLQuery + ') x'
within my procedure and that didn't work either.
Thanks for any suggestions`
QUOTENAMEand protecting your sql from injection. Dos and Don'ts of Dynamic SQL@mySQLQuerywith the values from the original line. I assume that that SQL works.SELECT ... INTOsyntax with a dynamic statement, the temporary table will only persist within the dynamic statement. Meaning you won't be able to access it outside of the dynamic execution ofsp_executesql.