Exit and rollback everything in script on error

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

    Try using RETURN. this will exit the script or procedure immediately and will not execute any of the following statements. You can use this in conjunction with BEGIN, ROLLBACK and COMMIT TRANSACTION statements to undo any data damage:

        BEGIN
        BEGIN TRANSACTION
    
        
        IF @@error <> 0
            begin
            RAISERROR ('first batch failed',16,-1)
            ROLLBACK TRANSACTION
            RETURN
            end
    
        
        IF @@error <> 0
            begin
            RAISERROR ('second batch failed',16,-1)
            ROLLBACK TRANSACTION
            RETURN
            end
    
        PRINT 'WIN!'
        COMMIT TRANSACTION
        END
    

提交回复
热议问题