zoukankan      html  css  js  c++  java
  • SQL Server 事务处理 回滚事务

    --创建表:

    GO

    CREATE TABLE [dbo].[tb1](

         [Id] [int] NOT NULL,

         [c1] [nvarchar](50) NULL,

         [c2] [datetime] NULL,

    CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED

    (

         [Id] ASC

    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] )

    ON [PRIMARY]

    GO

    --解决方案(一)

    declare   @iErrorCount   int  

    set @iErrorCount = 0  

    begin tran Tran_2015_09_30

      insert into tb1(Id, c1) values(1,'1')  

      set @iErrorCount=@iErrorCount+@@error  

      insert into tb1(Id, c1) values(2,'2')  

      set @iErrorCount=@iErrorCount+@@error  

      insert into tb1(Id, c1) values('xxxx3','3')  

      set @iErrorCount=@iErrorCount+@@error  

      insert into tb1(Id, c1) values(4,'4')  

      set @iErrorCount=@iErrorCount+@@error  

      insert into tb1(Id, c1) values(5,'5')  

      set @iErrorCount=@iErrorCount+@@error  

    if @iErrorCount=0

    begin    

      COMMIT TRAN Tran_2015_09_30 --执行事务

    end

    else  

    begin    

      ROLLBACK TRAN Tran_2015_09_30 --回滚事务

    end

    GO

    --解决方案(二)

    begin try
         begin tran Tran_2015_09_30
     
            insert into tb1(Id, c1) values(1,'1')
     
            insert into tb1(Id, c1) values(2,'2')
     
            insert into tb1(Id, c1) values('xxxx3','3')
     
            insert into tb1(Id, c1) values(4,'4')
     
            insert into tb1(Id, c1) values(5,'5')
     
        COMMIT TRAN Tran_2015_09_30
    end try
    begin catch
         raiserror 50005N'出错了'
         ROLLBACK TRAN Tran_2015_09_30  --回滚事务
    end catch

    GO

    --解决方案(三)

    --set XACT_ABORT ON   ---如果不设置该项为ON,在sql中默认为OFF,那么只只回滚产生错误的 Transact-SQL 语句;设为ON,回滚整个事务

    SET XACT_ABORT ON  --语句产生运行时错误,则整个事务将终止并回滚。
    Begin Tran
        INSERT INTO tb1(Id, c1) VALUES(1,'1')
        INSERT INTO tb1(Id, c1) VALUES('XX2','2') --此句产生错误时,就会回滚整个事务
    Commit Tran

    GO

    begin tran t1 ---启动一个事务

    update [water].[dbo].[ErrorInf]
    set ErrorMessage='test'
    where ID=6

    insert into [water].[dbo].[ErrorInf]([ID],ErrorMessage,[Description])
    Values(1,'test1','test1')

    commit tran t1  ---提交事务

    --//参考:

    1. EmanLee, Eman Lee's Space (blog, website)

     SQL Server 事务处理 回滚事务  ;

    2. 代码泪 SQL Server 事务及回滚事务

  • 相关阅读:
    python后端项目编码规范检查——pre-commit的使用
    centos7安装docker-compose
    python使用pandas将MySQL表数据写入Excel表格
    Sublime Text3中隐藏了菜单,怎么显示出来?
    Docker学习篇
    服务端|性能测试入门指南 (慎入: 6000 字长文)
    登录界面测试用例设计
    Date与String的转换,Date的加减计算(前一小时,前一个月、、、)
    关于SQL分页计算公式
    Java
  • 原文地址:https://www.cnblogs.com/wangfuyou/p/4849276.html
Copyright © 2011-2022 走看看