sqlserver 事务嵌套

参考 https://www.cnblogs.com/JentleWang/p/3654603.html

       https://blog.csdn.net/tuzhen007/article/details/11183961

create proc proc_example
as 
begin 
    --声明变量,存放当前已开启的事务数
    declare @exist_trancount int
    select @exist_trancount = @@trancount

    if @exist_trancount > 0
        --创建事务保存点
        save transaction tran_proc
    else
        --开启新事务
        begin transaction tran_proc
        
    /*
        存储过程业务处理代码
        ·········
    */
    if @@error<>0
        goto error


    if @exist_trancount = 0
        --提交事务
        commit tran tran_proc
        return 1
    error:
        --回滚事务或者事务保存点
        rollback transaction tran_proc
        return -1

end




  • 提交的事务不能撤销或回滚。
  • 当不存在打开的事务时,@@trancount 等于 0。
  • 执行 begin tran [tranName]语句将 @@trancount 增加 1。
  • 执行commit tran [tranName]语句将 @@trancount 减小 1。
  • 执行 rollback tran  会回滚整个事务并设置@@trancount 为 0。

猜你喜欢

转载自www.cnblogs.com/white-knight/p/8962477.html