Why are temporary tables not removed from tempdb in SQL Server?

Brijesh Patel picture Brijesh Patel · Jul 8, 2011 · Viewed 22.7k times · Source

I have created one stored procedure with 7 temporary tables and each temp table is dropped at the end of their own work.

I am calling the SP from one web service and same web service we are used for different instance.

I have dropped every temp table forcefully but when SP executes it will not delete any of the temporary table which are located in "tempdb/Temporary Table". And, when I open new instance of my application and try to execute same SP it will modify same temp tables.

This creates problem for me. it will lock the tables when SP execute simultaneously it will lock the table and my sp is not able to produce result and throw exception.

So I want to drop my temporary tables at the end of my operation. please help.

Answer

Jeremy Gray picture Jeremy Gray · Jul 8, 2011

I can't tell you why this is happening, but I have dealt with it before as well. Try cleaning up your tables at the beginning or end of the SP or using table variables.

IF object_id('tempdb..#TableName') IS NOT NULL DROP TABLE #TableName