How can I get the actual stored procedure line number from an error message?

前端 未结 9 2392
长情又很酷
长情又很酷 2020-12-04 07:02

When I use SQL Server and there\'s an error, the error message gives a line number that has no correlation to the line numbers in the stored procedure. I assume that the dif

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 07:31

    If you use a Catch Block and used a RAISERROR() for any code validation within the Try Block then the Error Line gets reported where the Catch Block is and not where the real error occurred. I used it like this to clear that up.

    BEGIN CATCH
      DECLARE @ErrorMessage NVARCHAR(4000);
      DECLARE @ErrorSeverity INT;
      DECLARE @ErrorState INT;
    
      SELECT 
         @ErrorMessage = ERROR_MESSAGE() + ' occurred at Line_Number: ' + CAST(ERROR_LINE() AS VARCHAR(50)),
         @ErrorSeverity = ERROR_SEVERITY(),
         @ErrorState = ERROR_STATE();
    
      RAISERROR (@ErrorMessage, -- Message text.
         @ErrorSeverity, -- Severity.
         @ErrorState -- State.
      );
    
    END CATCH
    

提交回复
热议问题