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

前端 未结 9 2391
长情又很酷
长情又很酷 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:23

    The long answer: the line number is counted from the CREATE PROCEDURE statement, plus any blank lines or comment lines you may have had above it when you actually ran the CREATE statement, but not counting any lines before a GO statement…

    I found it much easier to make a stored proc to play around with to confirm:

    GO
    
    -- =============================================
    -- Author:          <Author,,Name>
    -- Create date: <Create Date,,>
    -- Description:     <Description,,>
    -- =============================================
    CREATE PROCEDURE ErrorTesting
           -- Add the parameters for the stored procedure here
    AS
    BEGIN
           -- SET NOCOUNT ON added to prevent extra result sets from
           -- interfering with SELECT statements.
           SET NOCOUNT ON;
    
           -- Insert statements for procedure here
           SELECT 1/0
    
    END
    GO
    

    After you’ve created it, you can switch it to ALTER PROCEDURE and add some blank lines above the comments and above and below the first GO statement to see the effect.

    One very strange thing I noticed was that I had to run EXEC ErrorTesting in a new query window instead of highlighting it at the bottom of the same window and running… When I did that the line numbers kept going up! Not sure why that happened..

    0 讨论(0)
  • 2020-12-04 07:25

    In TSQL / Stored Procedures

    You may get an error such as:

    Msg 206, Level 16, State 2, Procedure myproc, Line 177 [Batch Start Line 7]

    This means that the error is on line 177 in the batch. Not 177 in the SQL. You should see what line number your batch starts on, in my case [7], and then you add that value to the line number to find what statement is wrong

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题