adopilot
adopilot

Reputation: 4500

In SQL Server 2005 emulating autonomous transaction

I have needs to keep some of log data in different tables even my transaction is rolled back.

I already learned that in SQL Server it is impossible do something like this

begin tran t1
insert ...
insert ...
select ...
       begin tran t2
         insert into log
       commit tran t2
rollback tran t1
select * from log -- IS EMPTY ALWAYS

So I try hacking SQL Server that I madded CLR which is going to export data need for LOG to local server disk in XML format. CLR Code is simple as it can be:

File.WriteAllText(fileName, xmlLog.Value.ToString());

Before I release this in production bases Ill love to hear your toughs about this technique.

Here are few questions:

Upvotes: 1

Views: 1906

Answers (1)

Solomon Rutzky
Solomon Rutzky

Reputation: 48786

I would suggest using a Table Variable as it is not affected by the Transaction (this is one of the methods listed in the blog noted by Martin below the question). Consider doing this, which will work in SQL Server 2005:

DECLARE @TempLog TABLE (FieldList...)

BEGIN TRY

    BEGIN TRAN

    INSERT...

    INSERT INTO @TempLog (FieldList...) VALUES (@Variables or StaticValues...)

    INSERT...

    INSERT INTO @TempLog (FieldList...) VALUES (@Variables or StaticValues...)

    COMMIT TRAN

END TRY
BEGIN CATCH

    IF (@@TRANCOUNT > 0)
    BEGIN
        ROLLBACK TRAN
    END

    /* Maybe add a Log message to note that we ran into an error */
    INSERT INTO @TempLog (FieldList...) VALUES (@Variables or StaticValues...)

END CATCH

INSERT INTO RealLogTable (FieldList...)
    SELECT FieldsList
    FROM @TempLog

Please note that while we are making use of the fact that Table Variables are not part of the transaction, that does create a potential situation where this code does a COMMIT but errors (or server crashes) before the INSERT INTO RealLogTable and you will have lost the logging for the data that did make it in. At this point there would be a disconnect as there is data but no record of it being inserted as far as RealLogTable is concerned. But this is just the obvious trade-off for being able to bypass the Transaction.

Upvotes: 3

Related Questions