2013-12-09 15 views
0

我試圖執行一個存儲過程,但我不確定如果我要走正確的方向。當我的IF條件爲真,也不會打印我raiseerrors ...SQL raisserror沒有顯示

set transaction isolation level repeatable read 

declare @return_value int = 0 
declare @someValue int = 3 
SET @retry = 3; 


--Keep trying to update 
--table if this task is 
--selected as the deadlock 
--victim. 
WHILE (@retry > 0) 
BEGIN 
BEGIN TRY 
    BEGIN TRANSACTION; 

    --check someValue 
    if @someValue < 5 
     begin 
      raiserror ('number is less than 5', 16,1) 
      ROLLBACK TRANSACTION 
      return 99    
     end 

    --all o.k , set retry 0 ending the while, commit transaction--               
    SET @retry = 0;     
    COMMIT TRANSACTION;    
END TRY 
    BEGIN CATCH 
    RAISERROR ('Errors found, please fix these errors and retry. Transaction  Rolled back', 16, 2); 
    -- Check error number. 
    -- If deadlock victim error, 
    -- then reduce retry count 
    -- for next update retry. 
    -- If some other error 
    -- occurred, then exit 
    -- retry WHILE loop. 
    IF (ERROR_NUMBER() = 1205) 
     SET @retry = @retry - 1; 
    ELSE 
     SET @retry = -1; 
    IF XACT_STATE() <> 0 
     ROLLBACK TRANSACTION; 
END CATCH; 
END; -- End WHILE loop.  

回答

0

第一RaIsError將由catch塊被消耗掉。如果你想保留它,或許添加額外的信息,你可以做這樣的事情:

set xact_abort, nocount on; 
set transaction isolation level repeatable read; -- Scope is this stored procedure. 
declare @LocalTransaction as Bit = case when @@TranCount = 0 then 1 else 0 end; 

declare @Return_Value as Int = 0; 
declare @SomeValue int = 3; 
declare @Retry as Int = 3; 

while @Retry > 0 
begin 
    begin try 
     if @LocalTransaction = 1 
      begin transaction; 

     if @SomeValue < 5 
      RaIsError ('Number is less than 5.', 16, 1); 

     set @Retry = 0; 
     if @LocalTransaction = 1 
      commit transaction; 
    end try 
    begin catch 
     if Error_Number() = 1205 
      set @Retry -= 1; 
     else 
     begin 
      set @Retry = -1; 
      -- Save the exception. 
      declare @ErrorLine as Int = Error_Line(); 
      declare @ErrorMessage as NVarChar(4000) = Error_Message(); 
      declare @ErrorNumber as Int = Error_Number(); 
      declare @ErrorProcedure as NVarChar(126) = Error_Procedure(); 
      declare @ErrorSeverity as Int = Error_Severity(); 
      declare @ErrorState as Int = Error_State(); 
      declare @NewLine as Char(2) = Char(13) + Char(10); -- '\r\n'. 

      -- Rollback only transactions when there is an active transaction that we started. 
      if Xact_State() <> 0 and @LocalTransaction = 1 
       rollback transaction; 

      -- Exit with the exception. 
      RaIsError('%s%s#%i [Proc: %s/Line %i]', @ErrorSeverity, @ErrorState, @ErrorMessage, @NewLine, @ErrorNumber, @ErrorProcedure, @ErrorLine); 
      return 99; 
     end; 
    end catch; 
end; 

注意,返回的錯誤也被catch塊,因爲在try塊代碼RAISERROR不該」後處理執行。