Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting into a temporary table from an Execute command

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
like image 410
Daniel Billingham Avatar asked Jul 17 '13 16:07

Daniel Billingham


1 Answers

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

like image 164
Nenad Zivkovic Avatar answered Sep 22 '22 19:09

Nenad Zivkovic