Abort insert/update operation in trigger using PL/SQL

懵懂的女人 提交于 2019-12-11 04:54:25

问题


I am to write a trigger that checks some information that is inserted/updated, compare them with data from database and if they are not correct, stops whole operation. I wrote before trigger (for each) and then threw application exception if something was wrong, but it was not working, becouse I read from the table that was updated, so I get ORA-04091 error.

And now I am wondering how to solve this? Now the only idea of mine is to write a before trigger that insert some necessary data into the package and read them with after trigger that won't be for each. But there's a problem how to abort this edition? If I make a rollback it will undo all operations in this transaction that I think is not smart. How would you solve this problem?


回答1:


Don't go there.

ORA-04091: table XXXX is mutating is generally a good indicator that whatever you're trying to do is too complex to be done reliably with triggers.

Sure, you could use a package array variable and a handful of triggers (ugh!) to get around this error, but your code will most likely:

  • be unmaintainable due to its complexity and the unpredictable nature of triggers
  • not respond well to a multi-user environment

This is why you should re-think your approach when you encounter this error. I advise you to build a set of procedures nicely grouped in a package to deal with inter-row consistency. Revoke all privileges to do DML the table directly and use only those procedures to modify it.

For instance your update procedure would be an atomic process that would:

  1. acquire a lock to prevent concurrent update on the same group of rows (for instance lock the room record in an hotel reservation application).
  2. check that the row to be inserted validates all business logic
  3. make all relevant DML
  4. rollbacks all its changes (and only its changes -- not the whole transaction) in case of error (easy with PL/SQL, just raise an error).


来源:https://stackoverflow.com/questions/15161064/abort-insert-update-operation-in-trigger-using-pl-sql

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