Exit and rollback everything in script on error

后端 未结 5 1675
我寻月下人不归
我寻月下人不归 2021-02-15 15:43

I have a TSQL script that does a lot of database structure adjustments but it\'s not really safe to just let it go through when something fails.

to make things clear:

5条回答
  •  长发绾君心
    2021-02-15 16:49

    When the error occurs, the transaction is rolled back automatically, and the current batch is aborted.

    Execution continues into the next batch, however. So all the stuff in the batches after the error gets executed. And then when you check for errors later, you try to rollback an already rolled back transaction.

    Also, to stop the entire script, not just the current batch, you should use:

    raiserror('Error description here', 20, -1) with log
    

    See my answer here for details on that one.

    So you need to check for @error after each batch, I think something like this should work:

    BEGIN TRANSACTION
    GO
    
    ALTER Stuff
    GO
    
    if @@error != 0 raiserror('Script failed', 20, -1) with log
    GO
    
    CREATE New Stuff
    GO
    
    if @@error != 0 raiserror('Script failed', 20, -1) with log
    GO
    
    DROP Old Stuff
    GO
    
    if @@error != 0 raiserror('Script failed', 20, -1) with log
    GO
    
    PRINT 'No Errors ... Committing changes'
    COMMIT TRANSACTION
    

提交回复
热议问题