SQL statements to ROLLBACK but Audit inserts to COMMIT

故事扮演 提交于 2019-12-25 09:25:53

问题


SQL Server 2012

I have a Master stored proc, which calls several other 'child' stored procs. The master proc encapsulates the child procs in a transaction.

Throughout the master and child procs, there are many inserts into an audit table.

If the process succeeds, I get a detaied chain of events. If the process fails and rolls back, I would like to have a record of the last child proc processed in the Audit table, but the whole thing is rolled back, including the audit data. Is there a way to selectively commit the audit inserts while rolling back the child proc changes?

Thanks


回答1:


That's pretty much a "nope". All work (inserts, updates, deletes) done on tables within a transaction are all-or-nothing.

An awkwardly manual option is to keep track of the data being processed in one or more variables, passing them back and forth between the procedures. If everything is committed, ignore the variables; if you have to roll back, you can dig the data you'd want to keep out of them.




回答2:


You can try using a table variable in the master procedure and inserting the return code of each child procedure into the table variable. Table variables are not affected by transactions, whereas temp tables are.

At the end of your master procedure, you can select from the table variable to return the results of your child procedures.



来源:https://stackoverflow.com/questions/41107449/sql-statements-to-rollback-but-audit-inserts-to-commit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!