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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With