Invalid object when selecting from temporary table I'm creating a temporary table called #PrevStatus. I've confirmed that the create statement is correct.

When I run,

exec (@TableQuery) 


which contains the table create statement and then right after

select * from #PrevStates


I get,

Invalid object name '#PrevStatus'


Why is this happening?
An option which I've used before is to create the temp table using some known fields that will always be the same, then alter the temp table using dynamic SQL to add in the additional columns that you only need in specific cases.  This way the temp table is created within scope, then altered via dynamic SQL.

CREATE TABLE #MyTable (ID int identity(1,1) primary key)

if @Something = 1 then
begin
     set @sql = 'alter table #MyTable add column ...'
     exec (@sql)
end
...
Your dynamic select statement goes down here somewhere.