Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly drop temp table or let SQL Server handle it

What is best practice for handling the dropping of a temp table. I have read that you should explicitly handle the drop and also that sql server should handle the drop....what is the correct method? I was always under the impression that you should do your own clean up of the temp tables you create in a sproc, etc. But, then I found other bits that suggest otherwise.

Any insight would be greatly appreciated. I am just concerned I am not following best practice with the temp tables I create.

Thanks,

S

like image 202
scarpacci Avatar asked Sep 08 '11 12:09

scarpacci


People also ask

Should you explicitly drop temp tables?

If you are wondering why it is not required to drop the temp table at the end of the stored procedure, well, it is because when the stored procedure completes execution, it automatically drops the temp table when the connection/session is dropped which was executing it.

Should we drop temp table in SQL Server?

No... you don't need to drop temp tables. That notwithstanding, I tend to do a conditional drop at the beginning of a sproc and it has nothing to do with any effect on the spoc. Rather, they are an artifact from development and testing prior to conversion to a stored procedure.

What happens if temp table is not dropped?

If I'm not mistaken, #temp table are implicitly dropped at the end of the stored procedure regardless of whether or not you explicitly drop it. ##temp tables (global ones) must be explicitly dropped. You could always reboot SQL Server, because that deletes the tempdb and rebuilds it on SQL Server start.


1 Answers

My view is, first see if you really need a temp table - or - can you make do with a Common Table Expression (CTE). Second, I would always drop my temp tables. Sometimes you need to have a temp table scoped to the connection (e.g. ##temp), so if you run the query a second time, and you have explicit code to create the temp table, you'll get an error that says the table already exists. Cleaning up after yourself is ALWAYS a good software practice.

EDIT: 03-Nov-2021

Another alternative is a TABLE variable, which will fall out of scope once the query completes:

DECLARE @MyTable AS TABLE (     MyID INT,      MyText NVARCHAR(256) )  INSERT INTO     @MyTable VALUES     (1, 'One'),     (2, 'Two'),     (3, 'Three')  SELECT     * FROM     @MyTable 
like image 191
HardCode Avatar answered Sep 23 '22 19:09

HardCode