lygyh9985825 发表于 2015-7-2 13:50:52

SQL Server 事务处理 回滚事务

   创建表:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE .(
    NOT NULL,
    (50) NULL,
    NULL,
CONSTRAINT PRIMARY KEY CLUSTERED
(
    ASC
)WITH (PAD_INDEX= OFF, STATISTICS_NORECOMPUTE= OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS= ON, ALLOW_PAGE_LOCKS= ON) ON
) ON
  
   解决方案(一)


declare   @iErrorCount   int
set @iErrorCount = 0
begin tran Tran_2008_10_07

insert into t1(Id, c1) values(1,'1')
set @iErrorCount=@iErrorCount+@@error

insert into t1(Id, c1) values(2,'2')
set @iErrorCount=@iErrorCount+@@error

insert into t1(Id, c1) values('xxxx3','3')
set @iErrorCount=@iErrorCount+@@error

insert into t1(Id, c1) values(4,'4')
set @iErrorCount=@iErrorCount+@@error

insert into t1(Id, c1) values(5,'5')
set @iErrorCount=@iErrorCount+@@error

if @iErrorCount=0
begin   
    COMMIT TRAN Tran_2008_10_07
end
else   
begin   
    ROLLBACK TRAN Tran_2008_10_07
end

  
   解决方案(二)

begin try
    begin tran Tran_2008_10_07

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

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

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

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

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

    COMMIT TRAN Tran_2008_10_07
end try
begin catch
    raiserror 50005N'出错了'
    ROLLBACK TRAN Tran_2008_10_07
end catch
  
页: [1]
查看完整版本: SQL Server 事务处理 回滚事务