即使出现错误,也要保持存储过程运行

时间:2015-02-10 14:30:12

标签: sql-server stored-procedures

我有一个存储过程,即使存在一些错误也需要运行。所以这里有一个小exameple

CREATE PROCEDURE FirstProcedure
@SomeParams 

AS BEGIN


Declare Db_Cursor Cursor For
Select * From #TmpR
Open Db_Cursor
Fetch Next From Db_cursor Into 
@SomaValues
While @@Fetch_Status = 0 
    Begin
    set @ERR = 0 
    exec [SecondProcedure] @SomaValues
    set @ERR = @@ERROR

    if @ERR <> 0 begin
       -- do some things in case of error 
     end
    Fetch Next From Db_Cursor Into 
@SomaValues

    End

END

如果第二个程序返回并且错误我将它捕获@ERR变量并执行其他操作,但我希望光标运行到表的末尾,因为它不是非常重要,如果2-使用SecondProcedure无法插入100.000中的3行?

我该怎么办?

1 个答案:

答案 0 :(得分:1)

使用Try/Catch

CREATE PROCEDURE FirstProcedure
@SomeParams 

AS BEGIN


Declare Db_Cursor Cursor For
Select * From #TmpR
Open Db_Cursor
Fetch Next From Db_cursor Into 
@SomaValues
While @@Fetch_Status = 0 
  Begin
    begin try
       exec [SecondProcedure] @SomaValues
    end try
    begin catch
      SELECT ERROR_NUMBER() AS ErrorNumber
            ,ERROR_SEVERITY() AS ErrorSeverity
            ,ERROR_STATE() AS ErrorState
            ,ERROR_PROCEDURE() AS ErrorProcedure
            ,ERROR_LINE() AS ErrorLine
            ,ERROR_MESSAGE() AS ErrorMessage;
    end catch

    Fetch Next From Db_Cursor Into @SomaValues
  End
  close db_cursor
  deallocate db_cursor

END