Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any benefit to explicitly dropping local temporary tables at the end of a stored procedure?

Consider the following psuedo T-SQL code (performed by a stored procedure):

CREATE TABLE #localTable ...

<do something with the temporary table here>

DROP TABLE #localTable;

The DROP TABLE statement is the last statement executed by the stored proceudre – is there any benefit to that statement?

Note that I'm not asking about dropping temporary tables (local or not) in the middle of the stored procedure (i.e. after the tables are no longer needed, but before the end of the stored procedure code) – that could seemingly have important benefits due to decreasing the memory required to continue executing the stored procedure. I want to know whether there's any benefit (or any effect, really, positive or negative) to explicitly dropping the table versus 'letting' SQL Server do so when the stored procedure finishes executing.

like image 283
Kenny Evitt Avatar asked Jan 12 '11 16:01

Kenny Evitt


People also ask

Should I drop temp tables in stored procedure?

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 you explicitly drop temp tables?

It's ok to explicitly include DROP TABLE or let SQL Server handle it for you each time the connection drops. If your stored procedures are already dropping temp tables, that's great.

What is the advantage of temporary table in SQL?

Global SQL temp tables are useful when you want you want the result set visible to all other sessions. No need to setup permissions. Anyone can insert values, modify, or retrieve records from the table. Also note that anyone can DROP the table.

What is the advantage of using a temporary table instead of?

Advantages of Temporary TablesYou can create a temporary table and insert, delete and update its records without worrying about whether you have sufficient rights to change data in permanent tables, or whether you might be accidentally doing so.


1 Answers

Theres a good detailed post on this here.

The temporary object is renamed to an internal form when DROP TABLE is executed, and renamed back to the same user-visible name when CREATE TABLE is encountered on the next execution. In addition, any statistics that were auto-created on the temporary table are also cached. This means that statistics from a previous execution remain when the procedure is next called.

like image 133
rageit Avatar answered Sep 21 '22 16:09

rageit