【发布时间】:2015-09-19 13:32:15
【问题描述】:
我有以下构造。我注意到错误号明显大于 0 的错误行在 while 循环结束时被删除。我不明白我在错误捕获方面出了什么问题。我是否需要在 catch 部分进行第二次提交来提交错误号的更新?
while @@FETCH_STATUS = 0
begin try
begin transaction
[...insert something into a table here...]
set @countrec = @countrec + @@rowcount
update Alarmtable
set success = 0
where Recno = @recno
commit transaction
end try
begin catch
if @@trancount > 0 rollback transaction
select @error = error_number()
, @errormsg = error_message()
update Alarmtable
set success = @error
where Recno = @recno
if @@trancount > 0 commit transaction
end catch
fetch next from listofrecords into
@recno, @alarmcontent
end /* while */
close listofrecords
deallocate listofrecords
delete Alarmtable
where success = 0
【问题讨论】:
-
删除 catch 块中的
if @@trancount > 0 commit transaction。我认为没有必要在那里拥有它 -
您能否发布您的整个代码,包括插入
Alarmtable的代码 -
删除 catch 块中的提交对我有用。由于我不明白的原因,这是导致错误行被删除的语句。我认为捕获中的第一次回滚会清空之前的所有内容。我的额外提交事务实际上将零提交给成功列。成功列中的错误号不需要提交即可正确保存。谢谢@kevchadders。
标签: sql-server tsql error-handling commit