My company is using SQL Server 2008. I am facing a Audit Table with transaction problems.
I have a stored procedure.
create proc MySP
as begin
insert into MY_TABLE values('Value1');
begin transaction TX_MY_SP
-- write to audit table permanently
insert into AUDIT_TABLE values('Value1 is inserted.');
commit transaction TX_MY_SP
end
I have a block of VB.net code
Using tx = New TransactionScope()
Using conn = New SqlConnection(MY_CONN_STR)
Using cmd = New SqlCommand("MySP", conn)
conn.Open()
cmd.ExecuteNonQuery()
Throw New ApplicationException("Always throw exception.")
End Using
End Using
tx.Complete()
End Using
However there is no record inserted into AUDIT_TABLE. I found the reason in MSDN http://msdn.microsoft.com/en-us/library/ms189336.aspx
My question is how can I insert records AUDIT_TABLE with stored procedure.
Thanks!
Any operation inside a transaction that rolled back rolls back as well. Not doing so would break transaction atomicity. Given that the activity you're auditing is being rolled back, is very likely that you actually want the audit to be rolled back anyway.
None the less, there are legitimate cases when one needs to have operations recorded outside the scope of the current transaction, like certain debug cases. There are known workarounds, like using event notifications for the user configurable event class, then using
sp_trace_generateevent
to cause the event notification activated procedure to run and record the audit. Because the profiler events are generated outside the transaction scope, the audit record does not get rolled back.