patternsqlMinor
Invalid object when selecting from temporary table
Viewed 0 times
invalidtemporaryobjectselectingwhenfromtable
Problem
I'm creating a temporary table called
When I run,
which contains the table create statement and then right after
I get,
Why is this happening?
#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 #PrevStatesI 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.