Error handling in long-running batch jobsBy Guest Authors on 29 January 2001 | Tags: Application Design , DMO Andy Pope, who cleverly uses the name andypope in the forums, posed a question on handling errors in long running batch jobs. Basically Andy wanted a way to store job log entries in a SQL Server log table that didn't get rolled back if the enclosing transaction failed. I really wasn't much help giving him an answer so the good Mr. Pope went and figured it own on his own. And boy do I like his solution! He posted his solution in the forums but I thought it deserved a little more explanation and attention.
You can find the original question and the discussion that followed here. Andy's solution involved using SQL Server's Distributed Management Objects (SQL-DMO) to create another connection to SQL Server from inside the transaction. Books Online describes SQL-DMO as a dual interface COM, in-process server implemented as a dynamic-link library (DLL). When creating a SQL-DMO application, you can use any OLE Automation controller or COM client development platform using C or C++. Andy was clever enough to figure out you could also use the sp_OA series of stored procedures to connect to SQL-DMO.
We'll start with a log table that looks like this:
and a stored procedure that looks like this. (At the bottom of this article is a link to a SQL Script with all this code.)
Pretty basic stuff so far. Now what we want to do is going to look something like this (written in my weak excuse for SQL Server psuedo-code):
I'm going to show you a couple of highlights from the script. Please download the full script and run it to see how it functions. First we log a message about starting the job, begin a transaction and put in a transaction to roll back (steps 1-3 above).
The next step is connect to SQL-DMO. We do that using the sp_OACreate stored procedure:
The variable That series of statements called the spi_BatchLog stored procedure outside the scope of the transaction. You'll see that entry in the log file even thought there is a ROLLBACK TRAN issued next.
That completes the script. As a last step we'll SELECT back the contents of the BatchLog table and see this:
Notice that our "Message from Inside Transaction" entry is present. Also notice that our "Roll Me Back" entry is not in the table. It would have been EntryID 2 which is missing from our result set. Thanks Andy for this great solution. I'm actually working on including it in a 10 million row update that I'm writing write now. You can download the complete script here. If you have any further discussion, please post them in the original thread. |
- Advertisement - |