Exit and rollback everything in script on error

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

    You could try something like this... If you are using Try block... The error level 16, (or most of application error), immediately transfers the control to the CATCH block without executing any further statements in the try block...

        Begin Transaction
    
    Begin Try
    
                        --  Do your Stuff
    
            If (@@RowCount <> 1) -- Error condition
            Begin
                Raiserror('Error Message',16,1)
            End
    
    
        Commit
    End Try
    Begin Catch
        IF @@Trancount > 0
        begin
            Rollback Transaction
        End
    
        Declare @ErrMsg varchar(4000), @Errseverity int
    
        SELECT @ErrMsg = ERROR_MESSAGE(),
              @ErrSeverity = ERROR_SEVERITY()
    
        RAISERROR(@ErrMsg, @ErrSeverity, 1)     
    End Catch
    

    Hope this helps...

提交回复
热议问题