Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write to a table in a new transaction in T-SQL

We have a requirement to log messages to a the database in our stored procedures - basically writing to a table. However if the transaction needs to be rolled back, we loose these logs.

Is there any way to write these logs (table inserts) in a new or different transaction to ensure they are persisted, regardless of the transaction of the current stored procedure?

like image 593
JohnnyB Avatar asked Nov 15 '25 16:11

JohnnyB


1 Answers

Abuse the fact that Variables(including table) are exempt from transactions. Store logs in a table var, insert from it after doing your regular transaction.

This should be enough for your logging needs.

One obvious downside of this is that you won't be able to monitor messages in "real time", using (nolock), so consider inserting both into your LogTable and Table Variable and only use the TableVariable on Rollback

like image 155
user6144226 Avatar answered Nov 18 '25 20:11

user6144226



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!