Search code examples
sql-serverstored-procedurestemp-tables

Can I recreate a temp table after dropping it?


Given:

code inside a stored proc:

select bleh
  into #tblTemp
  from FunctionThatReturnsTable('some','params')

-- do some stuff

drop table #tblTemp

-- Error on this command:
-- 'There is already an object named '#tblTemp' in the database.'
select bleh
  into #tblTemp
  from FunctionThatReturnsTable('some','other params')

Problem:

I can't recreate this temp table. My work around is to use #tmpTable1, #tmpTable2, #tempTable3 etc. Is there a way I can get around this? It would be nice just use one temp table each time.

If not, what is the reason for this?


Solution

  • As my comment reflected, I'm going to suggest that the answer is that you use a different #temp table name for each object that you create. It's kind of like saying to the doctor, "it hurts when I do this." His likely response is going to be, "stop doing that!"

    The reason this is a problem is that SQL Server's parser attempts to parse the entire batch in one shot. It can clearly see that you are trying to create the same #temp table multiple times, but ignores the DROP command in between (I can't tell you exactly why that is, as I don't have access to the source code). This is the same reason you can't do this:

    IF (1=1)
      CREATE TABLE #foo(i INT);
    ELSE
      CREATE TABLE #foo(i VARCHAR(32));
    

    The parser sees the two identical names, but can't really follow the IF/ELSE logic.

    In addition to avoiding the problems multiple identically-named #temp tables causes the parser, another benefit to using unique names is that they can be re-used if you don't explicitly drop them. This will lighten the load on tempdb in terms of metadata / locking.