Exit and rollback everything in script on error

后端 未结 5 1676
我寻月下人不归
我寻月下人不归 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:33

    I didn't use the raiseerror solution, because it failed as I didn't have admin permissions. I extended the noexec on/off solution with the transaction handling as follows:

    set noexec off
    
    begin transaction
    go
    
    
    go
    if @@error != 0 set noexec on;
    
    
    go
    if @@error != 0 set noexec on;
    
    <... etc>
    
    declare @finished bit;
    set @finished = 1;
    
    SET noexec off;
    
    IF @finished = 1
    BEGIN
        PRINT 'Committing changes'
        COMMIT TRANSACTION
    END
    ELSE
    BEGIN
        PRINT 'Errors occured. Rolling back changes'
        ROLLBACK TRANSACTION
    END
    

    Apparently the compiler "understands" the @finished variable in the IF, even if there was an error and the execution was disabled. However, the value is set to 1 only if the execution was not disabled. Hence I can nicely commit or rollback the transaction accordingly.

提交回复
热议问题