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

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

    you can get error message and error line in catch block like this:

    'Ms Sql Server Error: - ' + ERROR_MESSAGE() + ' - Error occured at: ' + CONVERT(VARCHAR(20),  ERROR_LINE())
    
    0 讨论(0)
  • 2020-12-04 07:16

    Actually this Error_number() works very well.

    This function starts counts from the last GO (Batch Separator) statement, so if you have not used any Go spaces and it is still showing a wrong line number - then add 7 to it, as in stored procedure in line number 7 the batch separator is used automatically. So if you use select Cast(Error_Number()+7 as Int) as [Error_Number] - you will get the desired answer.

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

    Helpful article on this issue:

    http://tomaslind.net/2013/10/15/line-numbers-in-t-sql-error-messages/

    "If you instead generate the script with Management Studio, the USE dbname statements and the settings for ANSI_NULLS and QUOTED_IDENTIFIER are added automatically. Remove these statements (9 rows) to get the line numbers correct in the script window:"

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

    IIRC, it starts counting lines from the start of the batch that created that proc. That means either the start of the script, or else the last "GO" statement before the create/alter proc statement.

    An easier way to see that is to pull the actual text that SQL Server used when creating the object. Switch your output to text mode (CTRL-T with the default key mappings) and run

    sp_helptext proc_name
    

    Copy paste the results into a script window to get syntax highlighting etc, and use the goto line function (CTRL-G I think) to go to the error line reported.

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

    Out of habit I place LINENO 0 directly after BEGIN in my stored procedures. This resets the line number - to zero, in this case. Then just add the line number reported by the error message to the line number in SSMS where you wrote LINENO 0 and bingo - you have the error's line number as represented in the query window.

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

    you can use this

    CAST(ERROR_LINE() AS VARCHAR(50))
    

    and if you want to make error log table you can use this :

    INSERT INTO dbo.tbname( Source, Message) VALUES ( ERROR_PROCEDURE(), '[ ERROR_SEVERITY : ' + CAST(ERROR_SEVERITY() AS VARCHAR(50)) + ' ] ' + '[ ERROR_STATE : ' + CAST(ERROR_STATE() AS VARCHAR(50)) + ' ] ' + '[ ERROR_PROCEDURE : ' + CAST(ERROR_PROCEDURE() AS VARCHAR(50)) + ' ] ' + '[ ERROR_NUMBER : ' + CAST(ERROR_NUMBER() AS VARCHAR(50)) + ' ] ' +  '[ ERROR_LINE : ' + CAST(ERROR_LINE() AS VARCHAR(50)) + ' ] ' + ERROR_MESSAGE())
    
    0 讨论(0)
提交回复
热议问题