create procedure dbo.P_TestTranscation
as
-- exec TestTranscation
-- select * from t1
-- delete from t1
declare @iErrorCount int
set @iErrorCount = 0
begin tran
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('xxxxx9',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
select 'bbb' as t15
ROLLBACK TRAN
return
end
print 'aaa'
COMMIT TRAN
此时执行
exec P_TestTranscation
将出现将 varchar 值 'xxxxx9' 转换为数据类型为 int 的列时发生语法错误。
存储过程停止执行,存储过程自动结束,当前事物回滚。
若将
insert into t1(Id, c1) values('xxxxx9',3)改为insert into t1(Id,c1) values(1,3)
将出现违反了 PRIMARY KEY 约束 'PK_t1'。不能在对象 't1' 中插入重复键。