How to get sql error in stored procedure

前端 未结 3 2009
醉话见心
醉话见心 2020-12-14 23:10

I\'m using SQL Server 2005. I created a stored procedure which works most of the time, but I found an instance of where it doesn\'t do what I want.

Currently, the c

相关标签:
3条回答
  • 2020-12-14 23:14

    use try ... catch and in catch block you can use ERROR_MESSAGE(), ERROR_LINE(), ERROR_PROCEDURE(), ERROR_STATE(), ERROR_SEVERITY(), ERROR_NUMBER() functions

    0 讨论(0)
  • 2020-12-14 23:36

    You could use a general Try/Catch and then construct more details about the error within the CATCH section e.g.

    DECLARE @DetailedErrorDesc VARCHAR(MAX)
    BEGIN TRY
    
    --tsql code goes here
    
    END TRY
    BEGIN CATCH
    
    SELECT @DetailedErrorDesc =         
      CAST(ERROR_NUMBER() AS VARCHAR) + ' : '+
      CAST(ERROR_SEVERITY() AS VARCHAR) + ' : ' +
      CAST(ERROR_STATE() AS VARCHAR) + ' : ' +
      ERROR_PROCEDURE() + ' : ' +
      ERROR_MESSAGE() + ' : ' +
      CAST(ERROR_LINE() AS VARCHAR);
    
    --Now you can decide what to do with the detailed error message....return it or log it etc
    
    END CATCH
    
    0 讨论(0)
  • 2020-12-14 23:37

    Here's part of a stored procedure template I use:

    /*  CREATE PROCEDURE...  */
    
    DECLARE
      @ErrorMessage   varchar(2000)
     ,@ErrorSeverity  tinyint
     ,@ErrorState     tinyint
    
    /*  Additional code  */
    
    BEGIN TRY
    
    /*  Your code here  */
    
    END TRY
    
    BEGIN CATCH
        SET @ErrorMessage  = ERROR_MESSAGE()
        SET @ErrorSeverity = ERROR_SEVERITY()
        SET @ErrorState    = ERROR_STATE()
        RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState)
    
        BREAK
    END CATCH
    
    /*  Further cleanup code  */
    

    Try/Catch blocks can be tricky but are much more thorough than @@error. More importantly, you can use the various error_xxx() functions within them. Here, I store the proper error message in variable @ErrorMessage, along with enough other data to re-raise the error. From here, any number of options are available; you could make @ErrorMessage an output variable, test for and handle specific errors, or build your own error messages (or adjust the existing ones to be clearer--you may get irritated finding out how often you'll want to do that). Other options will present themsleves.

    Something to look out for: in some situations, SQL will throw two error messages back to back... and error_message() will only catch the last one, which usually says something like "attempt to create object failed", with the real error given in the first error message. This is where building your own error message comes in.

    0 讨论(0)
提交回复
热议问题