告诉SQL Server错误在try ... catch中被“处理”

时间:2010-05-19 23:20:02

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

我想向SQL Server 2005表明,在我的BEGIN CATCH ... END CATCH块中,错误被“处理”......即清除错误。

这可能吗?考虑一下:

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.

感谢。 甲

1 个答案:

答案 0 :(得分:2)

并非所有错误都是可屏蔽的。您总是应该检查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