Inserting into a temporary table from an Execute command
execute, insert, sql, sql-server, temporary
Solution
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
Problem
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 ```