Technical Article

Custom Logging in a transaction

,

You get the idea. Operations on table variables don't get rolled back . Just backfill your log from the table variable and you know how far your transaction got. Of course you have to remember, that all entries in the log preceeding the error were rolled back. If you clear the runtime error on line 26, the transaction is committed and life goes on.

 

peter

create table #log_temp (msg varchar(255)) --main log tbl
declare @t table (msg varchar(255)) --our backup log
create table  #t (i int)
begin tran
begin try
insert #t values (1)
insert #log_temp values ( 'first')
insert @t values('first')

                insert #t values (2)
insert #log_temp values ( 'second')
insert @t values('second')

insert #t values (3)
insert #log_temp values ( 'third')
insert @t values('third')

insert #t values (4)
insert #log_temp values ('fourth')
insert @t values('fourth')

insert #t values (5)
insert #log_temp values ('fifth')
insert @t values('fifth')

insert #t values ('v') --introduce a runtime error
insert #log_temp values ('sixth')
insert @t values('sixth')

insert #t values (7)
insert #log_temp values ('seventh')
insert @t values('seventh')

insert #t values (8)
insert #log_temp values ('eighth')
insert @t values('eighth')
end try
begin catch
select * from #t -- data still there
rollback tran --clears everything including log_temp
                                select * from #log_temp --log is gone
                                select * from #t -- data is gone
insert #log_temp select * from @t --backfill the log 
insert #log_temp values('Rollback: '+error_message()) --insert the reason for rollback
end catch
if @@trancount>0
commit tran

drop table #t

select * from #log_temp -- log is back including the last error
drop table #log_temp

Rate

5 (1)

You rated this post out of 5. Change rating

Share

Share

Rate

5 (1)

You rated this post out of 5. Change rating