Inserting into a temporary table from an Execute command

Daniel Billingham picture Daniel Billingham · Jul 17, 2013 · Viewed 36.1k times · Source

I need to insert data from a select statement into a temporary table using the execute command.

if OBJECT_ID('tempdb..#x') is not null
drop table #x

Create Table #x(aaa nvarchar(max))

declare @query2 nvarchar(max)
set @query2 = 'SELECT [aaa] from IMP_TEMP'

INSERT #x
SELECT [aaa] from IMP_TEMP -- THIS WORKS
SELECT *from #x

INSERT #x
exec @query2 -- THIS DOES NOT WORKS, WHY?
SELECT *from #x

Answer

Nenad Zivkovic picture Nenad Zivkovic · Jul 17, 2013

You just need parenthesis around @query2 variable. EXEC command is to execute stored procedure, while EXEC() function is for executing dynamic sql taken as parameter.

INSERT #x
exec (@query2)
SELECT *from #x

Reading material