sql-server-2005 - 在try…catch中告诉SQL Server错误是 “handled”

标签 sql-server-2005 tsql error-handling try-catch

我想在我的BEGIN CATCH ... END CATCH块中向SQL Server 2005指示该错误已“处理” ...即清除该错误。

那可能吗?考虑一下:

begin transaction 
  begin try 
    begin transaction 

      select cast('X' as bit) 
    commit transaction 
   end try 
 begin catch rollback transaction 

   select error_number(), error_message() 
 end catch 

 commit transaction 

结果如下:
(0 row(s) affected)

(No column name)    (No column name)
245 Conversion failed when converting the varchar value 'X' to data type bit.

(1 row(s) affected)
Msg 3902, Level 16, State 1, Line 13
The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.

谢谢。
一种。

最佳答案

并非所有错误都是可以掩盖的。您总是应该检查XACT_STATE()并查看是否可以继续。某些错误(1205死锁是一个典型示例)将回滚事务,并且不允许您继续。

您所描述的(可以保留工作的循环)通常是在保存点的帮助下完成的:

begin transaction
begin try
while @loopcondition
begin
   save transaction loop;
   begin try
      -- process loop element here
   end try
   begin catch
     if xact_state() = -1
     begin
        -- whole transaction is doomed
        rollback;
        raiserror ('Aborting', ....);
     end
     else if xact_state() = 0
     begin
        -- trasaction was aborted by inner loop
        raiserror ('Aborted inside', ....);
     end  
     else if xact_state() = 1
     begin
       -- this error is recoverable, rollback to the savepoint and continue the loop
       rollback loop
     end
   end catch 
   -- continue loop here
   fetch next from ....
/*   
   -- batch commit here if batch committing
   if @batchsize 
   begin
      commit;
      begin transaction 
   end
*/
end
commit;
end try
begin catch
  -- if we get here, we could not handle the error inside the loop and continue
  if xact_state() != 0
    rollback
  raiserror('failed to process', ...)
end catch

关于sql-server-2005 - 在try…catch中告诉SQL Server错误是 “handled”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2870102/

相关文章:

database - 从数据库的所有表中删除所有记录

sql - SELECT FOR XML AUTO 并返回数据类型

sql-server - 在迭代循环中连接字符串: += does not work as expected

iphone - iOS:Sqlite 数据库错误:由于未捕获的异常 'NSInternalInconsistencyException' 而终止应用程序,原因: 'error preparing statement'

javascript - NodeJS - Events.js 无法读取未定义的每个属性

javascript - 错误处理程序的 JQuery 错误属性

sql-server - 使用 "WITH OVER"语句 - 如何在启动另一组记录时启动新的序列号?

sql-server-2005 - 将 SQL Server 2005 查询结果导出到 SQL INSERT 语句?

sql-server - SQL Server 2005 Express 其他用户看不到存储过程

sql-server - 在事务中执行语句而不在该事务中登记它