Search code examples
sql-servertemp-tables

Cannot create the same #temp table twice in the same batch


Wrote a very simple test case in SQLServer and don't quite understand why it doesn't work:

create table #temp(
  id int,
  val int)

insert into #temp values (1, 1), (2, 2)
select * from #temp

if object_id('tempdb..#temp') is not null
   drop table #temp

create table #temp(
  id int,
  val int)

insert into #temp values (1, 1), (2, 2)
select * from #temp

Solution

  • Please see the documentation, which states:

    If more than one temporary table is created inside a single stored procedure or batch, they must have different names.

    Your code yields the following error:

    Msg 2714, Level 16, State 1, Line 11
    There is already an object named '#temp' in the database.

    And this is not because the table has been dropped and can't be re-created; this code never gets executed, the parser actually sees you trying to create the same table twice (and it has no ability to see logic like your DROP command).

    Other than using two different #temp table names, another workaround would be to just create the table once, and truncate it when you're done with your first bit of code.