I have a scenario where I need something similar to .NET\'s try-catch-finally block.
On my try, I will CREATE a #temp table
, INSERT
Local temp tables (e.g., "#Temp") are automatically dropped when the SQL connection ends. It's good practice to include an explicit DROP
command anyway, but if it doesn't execute, the table will still be dropped.
If you must ensure that a DROP
executes as soon as possible, you'll have to repeat the DROP
command in a CATCH
clause, since there's no FINALLY
:
-- create temp table;
BEGIN TRY
-- use temp table;
-- drop temp table;
END TRY
BEGIN CATCH
-- drop temp table;
THROW; -- rethrow the error
END CATCH
Table variables are an alternative: they're dropped when the variable goes out of scope. However, table variables do not support statistics, so if the table variable is large and used in multiple queries, it may not perform as well as a temp table.