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
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.
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.
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.
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.
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
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