Koen
Koen

Reputation: 3686

SQL Server 2005 stored procedure with logging and error handling

I have a (SQL 2005) stored procedure that processes a giant table and groups old data from the past (up til one year ago). It has this main steps:

Now I want to log every run and every step in logging tables. However I start a transaction in the beginning so that I can rollback the whole batch if something goes wrong. But that would also rollback my logging which isn't what I want.

How can I resolve this?

Upvotes: 2

Views: 935

Answers (2)

gbn
gbn

Reputation: 432210

  • Use SET XACT_ABORT ON to force rollback
  • To catch all errors (where code runs), use TRY/CATCH blocks.

Then, you can simply log the errors in your CATCH blocks.

Example here (can add your own logging): Nested stored procedures containing TRY CATCH ROLLBACK pattern?

Personally, I find this more elegant than using table variables.

Upvotes: 1

Martin Smith
Martin Smith

Reputation: 453057

Log to a table variable as this doesn't get rolled back with the transaction then at the end of the procedure after commit or rollback insert the contents of the table variable into your permanent logging table.

Upvotes: 1

Related Questions