SQL Server TRY CATCH FINALLY

前端 未结 6 2113
执笔经年
执笔经年 2021-02-06 23:09

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

6条回答
  •  無奈伤痛
    2021-02-06 23:32

    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.

提交回复
热议问题