问题
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.
回答1:
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
回答2:
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.
回答3:
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.
回答4:
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
来源:https://stackoverflow.com/questions/6623846/why-are-temporary-tables-not-removed-from-tempdb-in-sql-server