0
votes

I create a trigger to check COUNT.

create or replace
TRIGGER TEST_TRG before INSERT OR UPDATE ON TEST
REFERENCING OLD AS OLD NEW AS NEW
FOR EACH ROW
DECLARE 
  AVAILABLE INTEGER;
BEGIN
IF UPDATING THEN
  IF(:new.STATUS = 600 OR :new.STATUS = 700) THEN
    SELECT COUNT(1) INTO AVAILABLE FROM TEST T WHERE T.IDDISPLAY = :new.IDDISPLAY 
      AND T.STATUS NOT IN (600,700);
    IF(AVAILABLE = 0) THEN
      InsertOrUpdateAnotherTable(:new.IDDISPLAY, :new.STATUS, 0);
    ELSE
      RETURN;
    END IF;
  END IF;
END IF;

After I change the status to 600 in Test Table, there are errors.

ORA-04091: table USER.TEST is mutating, trigger/function may not see it
ORA-06512: at "USER.TEST_TRG ", line 8
ORA-04088: error during execution of trigger 'USER.TEST_TRG'

I will insert or update another table if the condition is met.

The error is because I try to get COUNT of the current table when the trigger is triggering the same table. This will cause mutating happens.

I have try transaction_anonymous and Compound Trigger, but at the end still same error occurs.

Anyone can help me for another solution, please.

1
What is the business problem that you are trying to solve? Why do you need to query rows in the table other than the row that is being inserted or updated? Dependencies between rows in a table almost always indicates an underlying problem with the data model. - Justin Cave
Sorry for the misunderstanding. It is possible that more than 1 IDDISPLAY in the table and I need to make sure all status of the IDDISPLAY are 600 or 700, only I will Insert/udpate another table @JustinCave - king jia

1 Answers

0
votes

Firstly:

This below line

IF(AVAILABLE = 0) THEN

never will be reached, even if you could eliminate mutating error. Checking count like this: COUNT(1) INTO AVAILABLE will throw exception "no data found" when there is really no records you're quering.

Secondly: using compund trigger with section AFTER EACH ROW let you avoid mutating as Tom wrote http://www.dba-oracle.com/t_avoiding_mutating_table_error.htm:

Try this:

create or replace
TRIGGER TEST_TRG FOR INSERT OR UPDATE ON TEST
COMPOUND TRIGGER

AVAILABLE INTEGER;

AFTER EACH ROW IS
BEGIN
IF UPDATING THEN
 IF(:new.STATUS = 600 OR :new.STATUS = 700) THEN

  BEGIN
    SELECT COUNT(1) INTO AVAILABLE FROM TEST T WHERE T.IDDISPLAY = :new.IDDISPLAY 
    AND T.STATUS NOT IN (600,700);
  EXCEPTION 
WHEN NO_DATA_FOUND THEN
  InsertOrUpdateAnotherTable(:new.IDDISPLAY, :new.STATUS, 0);
  END;

 END IF;
END IF;
END AFTER EACH ROW;
END TEST_TRG;