HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Invalid object when selecting from temporary table

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
invalidtemporaryobjectselectingwhenfromtable

Problem

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?

Solution

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.

Code Snippets

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.

Context

StackExchange Database Administrators Q#80860, answer score: 3

Revisions (0)

No revisions yet.