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
Question
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
La 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
Autres conseils
Unlike Alex K comments, a local temporary table is visible inside all inner scopes within a connection. The following snippet runs fine:
create table #tbl (id int)
exec ('select * from #tbl')
You can also use insert ... exec
with temporary tables:
create table #tbl (id int)
insert #tbl values (3), (1), (4)
insert #tbl exec ('select id from #tbl')
If this doesn't work for you, please post the exact error. One likely culprit is that insert ... exec
demands that the column definition of the table and the query match exactly.
INSERT #x
exec @query2 -- THIS DOES NOT WORKS, WHY?
SELECT *from #x
Have you tried using the correct synthax:
INSERT #x
exec (@query2)
SELECT *from #x