Why can’t you do this and is there are work around?
You get this error.
Msg 2714, Level 16, State 1, Line 13 There is already an object named ‘#temptable’ in the database.
declare @x int set @x = 1 if (@x = 0) begin select 1 as Value into #temptable end else begin select 2 as Value into #temptable end select * from #temptable drop table #temptable
This is a two-part question and while Kev Fairchild provides a good answer to the second question he totally ignores the first – why is the error produced?
The answer lies in the way the preprocessor works. This
is resolved into a parse-tree that is directly equivalent to
and this puts #symbol into the local scope’s name table. The business with _sessionid is to provide each user session with a private namespace; if you specify two hashes (##symbol) this behaviour is suppressed. Munging and unmunging of the sessionid extension is (ovbiously) transparent.
The upshot of all this is that multiple INTO #symbol clauses produce multiple declarations in the same scope, leading to Msg 2714.