Results 1 to 3 of 3

Thread: How catch the db exception in stored procedure

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jun 2007
    Posts
    241

    Thumbs up How catch the db exception in stored procedure

    Hi,

    I am using Sql Server 2005. I have one doubt. I write procedure for multiple queries.

    BEGIN TRAN
    BEGIN TRY

    query 1

    query 2

    query 3

    COMMIT TRAN

    END TRY
    BEGIN CATCH
    ROLLBACK TRAN

    END CATCH

    Now i am getting error in the query 1 or 2 or 3 . that is data base error For eg autoid parameter is not supplied . How can i catch the error? And what command is used for this one. I need this one very urgent.Hope your's reply.

    Thanks
    Failing to plan is Planning to fail

  2. #2
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,657

    Re: How catch the db exception in stored procedure

    You need to use @@Error.

    When you run an sql statement in a stored proc immediately afterwards check if @@Error equals Zero. If Not then the statement has errored.

    Here is a basic example.

    Code:
    BEGIN TRAN
    
    SELECT * FROM TEST
    
    IF @myERROR != 0 GOTO HANDLE_ERROR
    
    COMMIT TRAN
    
    HANDLE_ERROR:
    
    ROLLBACK TRAN
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  3. #3
    PowerPoster
    Join Date
    Oct 2002
    Location
    British Columbia
    Posts
    9,758

    Re: How catch the db exception in stored procedure

    SQL Server 2005 introduced better error handling than @@Error.

    In the Catch block execute a select statement that returns the error information.

    Code:
        SELECT 
            ERROR_NUMBER() AS ErrorNumber,
            ERROR_SEVERITY() AS ErrorSeverity,
            ERROR_STATE() as ErrorState,
            ERROR_PROCEDURE() as ErrorProcedure,
            ERROR_LINE() as ErrorLine,
            ERROR_MESSAGE() as ErrorMessage;
    http://msdn.microsoft.com/en-us/libr...6(SQL.90).aspx

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width