3

i had a major screw up in my latest patch. An update condition was incomplete and i updated multiple rows by accident.

What i wanna do now is to prevent this by setting a constraint for a table wich cause an exception as soon as i try to update multiple rows. Optionally with specific parameters.

Is there a way to do this in oracle 11.2 ?

Jan S.
  • 331
  • 1
  • 3
  • 10

2 Answers2

5

You can accomplish this by using a compound trigger:

CREATE OR REPLACE TRIGGER TABLE1_FAIL_MULT_UPDATES_TRG
  FOR UPDATE ON TABLE1
COMPOUND TRIGGER
  nUpdate_count  NUMBER;

  BEFORE STATEMENT IS
  BEGIN
    nUpdate_count := 0;
  END BEFORE STATEMENT;

  BEFORE EACH ROW IS
  BEGIN
    IF UPDATING THEN
      nUpdate_count := nUpdate_count + 1;

      IF nUpdate_count > 1 THEN
        RAISE_APPLICATION_ERROR(-20100, 'Attempted to update more than 1 row');
      END IF;
    END IF;
  END BEFORE EACH ROW;

END TABLE1_FAIL_MULT_UPDATES_TRG;

You can read further on compound triggers here.

Best of luck.

Jeromy French
  • 11,812
  • 19
  • 76
  • 129
  • Wow, forgot about compound triggers. It is exactly what the op needs. – Florin Ghita Nov 05 '15 at 13:14
  • It would be interesting to see what happens in case of statement restart as noticed in the answer I mentioned. http://tkyte.blogspot.ro/search?q=statement+restart – Florin Ghita Nov 05 '15 at 14:22
0

You can use the Answer on this question which offer a solution with three triggers and package variable to count the number of rows affected. In the third trigger, if the number of rows is greater than one then raise an exception. The entire statement will be rolled back.

This is also safe for concurrency because package variables are "stored" session level.

Community
  • 1
  • 1
Florin Ghita
  • 17,525
  • 6
  • 57
  • 76