SQL 异常捕获和事务回滚

/*---------------------------------------------
try 配合事务tran 异常消息和事务回滚*/
BEGIN TRY
    BEGIN TRAN 事务名;/*开始事务*/
    
    
/*------------------------------

    业务代码
    
-------------------------------*/
 

    COMMIT TRAN 事务名;/*提交事务*/
END TRY 
BEGIN CATCH 


    ROLLBACK TRAN 事务名;/*事务回滚*/
    
    /*异常接收和处理*/
    DECLARE @ErrorMessage NVARCHAR(4000),@ErrorSeverity INT,@ErrorState INT;
    
    /*获取异常消息提示*/
    SELECT
    @ErrorMessage = ERROR_MESSAGE(), 
    @ErrorSeverity = ERROR_SEVERITY(),
    @ErrorState = ERROR_STATE();
    
    /*报错提示*/
    RAISERROR (@ErrorMessage, -- Message text.
    @ErrorSeverity, -- Severity.
    @ErrorState -- State.
    );
    
END CATCH

 

posted @ 2022-03-04 10:55  蓝雨冰城  阅读(159)  评论(0编辑  收藏  举报