【问题标题】:T-SQL error handling with try catch rollback, error rows were deleted使用 try catch 回滚的 T-SQL 错误处理,错误行被删除
【发布时间】: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


【解决方案1】:

删除了提交事务,错误条目不再被删除。谢谢@kevchadders。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-25
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 2018-10-29
    相关资源
    最近更新 更多