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

两盒软妹~` 提交于 2019-12-01 20:46:37

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
Azhar Iqbal

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.

WaitForPete

To force dropping of temp tables use

BEGIN TRY DROP #MyTable END TRY BEGIN CATCH END CATCH

Ugly but effective. Use a separate TRY for each temporary table.

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

I think this will not work as we know sql server store temp table name with adding some extra character. if exists(select 1 from tempdb.sys.tables where name like '#TableName%') DROP TABLE #TableName

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!