SQL SERVER存储过程中使用事务与捕获异常

时间:2025-01-09 16:07:26

https://www.douban.com/note/559596669/

格式类似于

CREATE PROCEDURE YourProcedure
AS
BEGIN
    SET NOCOUNT ON;

BEGIN TRY---------------------开始捕捉异常
       BEIN TRAN------------------开始事务
        UPDATE A SET A.names = B.names FROM 表1 AS A INNER JOIN 表2 AS B ON A.id = B.id

UPDATE A SET A.names = B.names FROM 表1 AS A INNER JOIN 表2 AS B ON A.TEST = B.TEST

COMMIT TRAN -------提交事务
    END TRY-----------结束捕捉异常
    BEGIN CATCH------------有异常被捕获
        IF @@TRANCOUNT > 0---------------判断有没有事务
        BEGIN
            ROLLBACK TRAN----------回滚事务
        END
        EXEC YourLogErrorProcedure-----------记录存储过程执行时的错误信息,自定义
    END CATCH--------结束异常处理
END