Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 793121
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T22:06:08+00:00 2026-05-14T22:06:08+00:00

I am not an expert on SQl Server. Is this a valid pattern for

  • 0

I am not an expert on SQl Server. Is this a valid pattern for handling errors in a batch of SELECT, INSERT…in SQl SERVER ? (I use v.2008)

BEGIN TRANSACTION
    BEGIN TRY
       -- statement 1
       -- statement 2
       -- statement 3
       COMMIT TRANSACTION
    END TRY

    BEGIN CATCH
       ROLLBACK TRANSACTION
    END CATCH

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T22:06:09+00:00Added an answer on May 14, 2026 at 10:06 pm

    I use something like this:

    CREATE PROCEDURE  ErrorHandlingPattern
    (     @intParam      int
         ,@varcharParam  varchar(10)
         ,@dateParam     datetime
    ) 
    AS
    
    BEGIN TRY
        SET NOCOUNT ON
        DECLARE @Rows              int           --store @@ROWCOUNT in this
               ,@ErrorMsg          varchar(500)  --temp string to build the contents of messages passed into RAISERROR calls
               ,@LogInfo           varchar(5000) --will hold any info necessary for error debugging, append to this throughout the procedure with important info
               ,@TransactionCount  int           
    
        SELECT @TransactionCount=@@TRANCOUNT
              ,@LogInfo='@intParam='     +ISNULL(''''+CONVERT(varchar(10),  @intParam       )+'''','NULL')
                     +', @varcharParam=' +ISNULL(''''+                      @varcharParam    +'''','NULL')
                     +', @dateParam='    +ISNULL(''''+CONVERT(varchar(10),  @dateParam,121  )+'''','NULL')
                     +'; @@TRANCOUNT='   +ISNULL(''''+CONVERT(varchar(10),  @@TRANCOUNT     )+'''','NULL')
    
        --validate parameters
        IF @intParam ....
        BEGIN --logical error
            SET @ErrorMsg='Error, invalid value for @intParam: '+ISNULL(''''+CONVERT(varchar(10),@intParam)+'''','NULL')
            RAISERROR(@ErrorMsg,16,1) --send control to the BEGIN CATCH block
        END
    
        IF @TransactionCount=0  --if we are already in a transaction, no need to start another, nesting transactions +rollback=warnings about transaction count not being the same as when the procedure started.
        BEGIN
            BEGIN TRANSACTION
        END
    
        --do your work here....
        INSERT/UPDATE/DELETE...
        SELECT @Rows=@@ROWCOUNT
    
        IF @Rows!=ExpectedValue
        BEGIN --logical error
            SET @ErrorMsg='Error, INSERT/UPDATE/DELETE of tableXYZ resulted in '+ISNULL(''''+CONVERT(varchar(10),@Rows)+'''','NULL')+' rows affected'
            RAISERROR(@ErrorMsg,16,1) --send control to the BEGIN CATCH block
        END
    
        --append improtant info to log string
        SET @LogInfo=ISNULL(@LogInfo,'')+'; INSERT/UPDATE/DELETE of tableXYZ resulted in '+ISNULL(''''+CONVERT(varchar(10),@Rows)+'''','NULL')+' rows affected'
    
        IF @TransactionCount=0 --only end the transaction if it started here
        BEGIN
            COMMIT --put in try block to be able to catch any problems committing
        END
    END TRY
    BEGIN CATCH
    
        IF XACT_STATE()!=0 --if there is any error end the transaction ASAP
        BEGIN
            ROLLBACK TRANSACTION
        END
    
        --will echo back the complete original error message
        DECLARE @ErrorMessage nvarchar(400), @ErrorNumber int, @ErrorSeverity int, @ErrorState int, @ErrorLine int
        SELECT @ErrorMessage = N'Error %d, Line %d, Message: '+ERROR_MESSAGE(),@ErrorNumber = ERROR_NUMBER(),@ErrorSeverity = ERROR_SEVERITY(),@ErrorState = ERROR_STATE(),@ErrorLine = ERROR_LINE()
        RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorNumber,@ErrorLine)
    
        --because the transaction was ROLLBACKed this insert will be recorded in the database
        INSERT INTO YourErrorLog (...) VALUES (...ISNULL(@ErrorMessage,'')+ISNULL(@LogInfo,''))
    
        RETURN 999
    
    END CATCH
    
    RETURN 0
    GO
    

    Since you are just doing a batch of a batch of SELECT, INSERT, you can just remove the CREATE PROCEDURE and parameter declarations and have the first line start at BEGIN TRY. Also, because you are not creating a procedure, replace any RETURN statements with GOTO TheEnd and add a TheEnd: label at the script’s bottom.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 425k
  • Answers 425k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I think there is likely to be a slight conceptual… May 15, 2026 at 12:12 pm
  • Editorial Team
    Editorial Team added an answer You're not using existential quantification here. You're using rank N… May 15, 2026 at 12:12 pm
  • Editorial Team
    Editorial Team added an answer it will never work if you're doing the decryption on… May 15, 2026 at 12:12 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.