第一种:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->declare @iErrorCount int
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
第二种:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->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
第三种:
SET XACT_ABORT ON ----语句产生运行时错误,则整个事务将终止并回滚。 Begin Tran INSERT INTO t1(Id, c1) VALUES(1,'1') INSERT INTO t1(Id, c1) VALUES('XX2','2') --此句产生错误时,就会回滚整个事务 Commit Tran