I want to create a temporary table in a dynamic query and use it afterwards. It will be created from a permanent table:
create table t (a integer);
insert into t values (1);
And the temp table creation is like this:
declare @command varchar(max) = '
select *
into #t
from t
;
select * from #t;
';
execute (@command);
When the @command is executed the select from the temporary table works.
Now if I select from the temporary table an error message is shown:
select * from #t;
Invalid object name '#t'
If the temporary table is created outside of the dynamic query it works:
select top 0 *
into #t
from t
declare @command varchar(max) = '
insert into #t
select *
from t
';
execute (@command);
select * from #t;
Is it possible to persist a dynamically created temporary table?
You can also create global temporary tables. For example, ##MyTemp.
But, global temporary tables are visible to all SQL Server connections.