I need to make two seperate triggers (it is required to be made that way), one for the inserts and one for the updates on a table contaning different stages of a project which id’s comes from another table. Whenever a project stage is updated, I need to make sure the total budget of the stages of a project isn’t higher than the one of the actual project. Here is the code of the table creation and the one of the triggers.
CREATE TABLE Projet (
id_projet integer PRIMARY KEY,
nom_projet varchar(50) NOT NULL,
date_debut date NOT NULL,
date_fin date NOT NULL,
budget numeric(10,2) NOT NULL
);
CREATE TABLE Projet_phase (
id_projet integer,
id_phase integer UNIQUE,
nom_phase varchar(50) NOT NULL,
date_debut date NOT NULL,
date_fin date NOT NULL,
budget numeric(10,2) NOT NULL,
PRIMARY KEY (id_projet, id_phase),
FOREIGN KEY (id_projet) REFERENCES Projet(id_projet)ON DELETE CASCADE
);
-- Somme budgets phases < budget projet pour projet_phase
CREATE OR REPLACE TRIGGER T_validerbudget_Insertion_projetphase
BEFORE INSERT ON Projet_phase
FOR EACH ROW
DECLARE
budget_total NUMBER := 0;
budget_projet Projet.budget%TYPE;
BEGIN
SELECT NVL((sum(budget) + :NEW.budget), 0) total
INTO budget_total
FROM projet_phase
WHERE id_projet = :NEW.id_projet;
SELECT budget INTO budget_projet FROM Projet WHERE id_projet = :NEW.id_projet;
IF budget_total > budget_projet THEN
RAISE_APPLICATION_ERROR(
-20001,
'IMPOSSIBLE D''AJOUTER LA PHASE CAR LA SOMME DES BUDGETS DES PHASES DÉPASSE CELUI DU PROJET'
);
END IF;
END;
/
CREATE OR REPLACE TRIGGER T_validerbudget_Insertion_projetphase
BEFORE UPDATE ON Projet_phase
FOR EACH ROW
DECLARE
budget_total NUMBER := 0;
budget_projet Projet.budget%TYPE;
BEGIN
SELECT NVL((sum(budget) + :NEW.budget), 0) total
INTO budget_total
FROM projet_phase
WHERE id_projet = :NEW.id_projet AND id_phase <> :NEW.id_phase;
SELECT budget INTO budget_projet FROM Projet WHERE id_projet = :NEW.id_projet;
IF budget_total > budget_projet THEN
RAISE_APPLICATION_ERROR(
-20001,
'IMPOSSIBLE DE MODIFIER LA PHASE CAR LA SOMME DES BUDGETS DES PHASES DÉPASSE CELUI DU PROJET'
);
END IF;
END;
/
The first one seems to work perfectly, but the second one gives me this error :
ORA-04091 table string.string is mutating, trigger/function may not see it
I’m very much confused about a few things :
- How come only one of them as such and issue instead of both of them not working for this reason
- How am I supposed to test information of a table with a trigger if it can’t access the data of said table
I tried using the trigger after the update instead, in case the transaction would not be seen as still being processed, therefore giving me access to the table, but it still doesn’t. Also tried adding PRAGMA AUTONOMOUS_TRANSACTION as it was mentionned quite often. Howerver it didn’t change anything.