SQL Server 事务及回滚事务
第一种:
declare @iErrorCount int
set @iErrorCount = 0
begin tran Tran1
insert into t1(Id, c1) values(1,'1')
set @iErrorCount=@iErrorCount+@@error
insert into t1(Id, c1) values('XX2','2')
set @iErrorCount=@iErrorCount+@@error
if @iErrorCount=0
begin
COMMIT TRAN Tran1 --执行事务
end
else
begin
ROLLBACK TRAN Tran1 --回滚事务
end
set @iErrorCount = 0
begin tran Tran1
insert into t1(Id, c1) values(1,'1')
set @iErrorCount=@iErrorCount+@@error
insert into t1(Id, c1) values('XX2','2')
set @iErrorCount=@iErrorCount+@@error
if @iErrorCount=0
begin
COMMIT TRAN Tran1 --执行事务
end
else
begin
ROLLBACK TRAN Tran1 --回滚事务
end
第二种:
Begin Try
Begin Tran Tran1
insert into t1(Id, c1) values(1,'1')
insert into t1(Id, c1) values('XX2','2') --此句产生错误
COMMIT TRAN Tran1
END Try
Begin Catch
raiserror 50005N'出错了'
ROLLBACK TRAN Tran1 ---出错后调用回滚
END Catch
Begin Tran Tran1
insert into t1(Id, c1) values(1,'1')
insert into t1(Id, c1) values('XX2','2') --此句产生错误
COMMIT TRAN Tran1
END Try
Begin Catch
raiserror 50005N'出错了'
ROLLBACK TRAN Tran1 ---出错后调用回滚
END Catch
第三种:
SET XACT_ABORT ON ----语句产生运行时错误,则整个事务将终止并回滚。
Begin Tran
INSERT INTO t1(Id, c1) VALUES(1,'1')
INSERT INTO t1(Id, c1) VALUES('XX2','2') --此句产生错误时,就会回滚整个事务
Commit Tran
Begin Tran
INSERT INTO t1(Id, c1) VALUES(1,'1')
INSERT INTO t1(Id, c1) VALUES('XX2','2') --此句产生错误时,就会回滚整个事务
Commit Tran
阅读全文
类别:sql ado 存储过程 查看评论
posted on 2010-08-19 13:51 dreamontheway 阅读(198) 评论(0) 编辑 收藏 举报