SQL Server: affect other transactions?

Posted on

Question :

I’d be surprised if this existed, but will ask just in case. Is there some mechanism which would allow one transaction to affect another (outside) transaction? For example:

BEGIN TRY
  BEGIN TRAN
    -- Run updates 01
    INSERT INTO dbo.Log (Text) VALUES ('Updates 01 - big success');

    -- Run updates 02
    INSERT INTO dbo.Log (Text) VALUES ('Updates 02 - big success');

    -- and so on...
  COMMIT
END TRY
BEGIN CATCH
  ROLLBACK
  INSERT INTO dbo.Log (Text) VALUES ('At a certain step there was a problem: ' + ERROR_MESSAGE());
END CATCH

Of course, in case of errors we lose the success log entries done inside the transaction and are left only with the last (error) message inserted after the rollback took place.
Is there a way to make those INSERT INTO dbo.Log statements “persistant” before the transaction finishes?
I guess, if it were, it would fly in the face of proper transaction control, so I on some level hope this doesn’t exist, but maybe somewhere in the category of tricks?

Thank you.

Answer :

Assuming they are running on the same session, no, as you’ve already said. Are there ways around it? Sure, take it out of that session by plopping the messages in a service broker queue with an activated stored procedure. The only part I’m not quite sure on is if the WITH LOG part of raiserror would be subject to that or not – though you probably don’t want to write the results to the errorlog.

It could also be shortened so that each part is its own transaction but that may not be suitable for your needs.

Leave a Reply

Your email address will not be published.