Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 720
Brijesh Patel Avatar asked Jan 29 '26 04:01

Brijesh Patel


2 Answers

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
like image 99
Jeremy Gray Avatar answered Jan 31 '26 21:01

Jeremy Gray


This can occur in case if you have used many Temp tables and you have some Error in between of Your sp and your drop statement could not executed.
So its always best practice to use

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

in start of SP.

like image 24
Azhar Iqbal Avatar answered Jan 31 '26 22:01

Azhar Iqbal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!