I am importing an intermediate result of query into a temp table for further use, so I used a #temp table to maintain the same schema as
select * into # temp from schema.tableName where 1<>1;
insert into # temp from exec(table)
While I am doing this statement as a variable to pass the different tableName its not working
SET @TEMPSCHEMA = 'SELECT * INTO #temp FROM ' + @PKSchema + '.dbo.' + @PKTableName + ' WHERE 1<>1;'
exec(@TEMPSCHEMA)
INSERT INTO #temp
EXEC ( @SELECTSTATEMENT
)
however after exec statement it is not taking the values to the temp table.
it is showing the invalid object id #temp
This is because the scope of the
EXECstatement is different to the scope of the containing sproc. That is, your call toEXECis creating the temporary table, and then it’s being automatically dropped as the scope for theEXECis left. You basically have to do the whole lot inside the oneEXECstatement: