If you’ve worked with building a CLR trigger for MsSQL, then there are decent odds you’ve seen this come back to the message window while testing the trigger inside Microsoft SQL Management Studio:

The context transaction which was active before entering user defined routine, trigger or aggregate “[CLR trigger name]” has been ended inside of it, which is not allowed. Change application logic to enforce strict transaction nesting.

So, after you finish pulling your brains out one hair at a time, do this:

  1. Put a try { } catch(Exception as ex) { } around the block of code that is executing commands into the database
  2. Use the SqlContext.Pipe.SendMessage(ex.Message) to send the message to the Management Studio message window
  3. Figure out why your query is crashing and causing the entire transaction to rollback, therefore causing this problem.

As you can see, this problem arises when there is a problem with one of the queries being executed in the Transaction (you inherit the Transaction from when the trigger is invoked). When a trigger throws a rollback inside the transaction, it causes an exception.

I also tried to begin another transaction (inspired by the concept of “nested transactions”) but that didn’t seem to work. I have one other thing I plan on trying if this problem flares up again (which I have a feeling it will). I’m going to wrap every command text in a try catch block, for the SQL database. Since I have all of my commands accessing the database at a centralized method, this should be fairly easy to implement. I think this will prevent such a rollback, but havn’t tried it so I’m not sure. If you try it first, let me know!

Here’s some syntax for SQL Try/Catch statements:

  1. BEGIN TRY
  2.     – Generate divide-by-zero error.
  3.     SELECT 1/0;
  4. END TRY
  5. BEGIN CATCH
  6.     – Execute your error logging routine here.
  7. END CATCH;
Tags: , , , , , , ,
2 Responses to “MsSQL Rant 2: Context transaction [blah blah blah] enforce strict transaction nesting.”
  1. thatoneguy.net » Wow… color me shocked… says:

    [...] but welcome…  Most of these visitors are here for the programming stuff (specifically the SQL trigger context post) I certainly wouldn’t mind some comments on if you think I’ve got something [...]

  2. John says:

    Do you really think this is new thing? Your blog is really good to me, I read it to get useful info, but sometimes I’m bored to tears.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>