I'm trying to do a trigger but I get a mutating table error. The SQL code is something like this:
CREATE OR REPLACE TRIGGER CHK_Apartado_D
BEFORE INSERT OR UPDATE ON CONTRACTS
FOR EACH ROW
DECLARE
errorvisualizacion EXCEPTION;
local_enddate DATE;
BEGIN
SELECT enddate INTO local_enddate FROM CONTRACTS WHERE clientid=:new.clientid;
IF local_enddate > SYSDATE OR local_enddate IS NULL
THEN
UPDATE CONTRACTS SET enddate = SYSDATE - 1 WHERE clientid=:new.clientid;
END IF;
END CHK_Apartado_B;
/
And the error that I get is this:
Informe de error -
Error SQL: ORA-04091: table HR.CONTRACTS is mutating, trigger/function may not see it
ORA-06512: at "HR.CHK_APARTADO_D", line 5
ORA-04088: error during execution of trigger 'HR.CHK_APARTADO_D'
ORA-06512: at "HR.CHK_APARTADO_D", line 8
ORA-04088: error during execution of trigger 'HR.CHK_APARTADO_D'
04091. 00000 - "table %s.%s is mutating, trigger/function may not see it"
*Cause: A trigger (or a user defined plsql function that is referenced in
this statement) attempted to look at (or modify) a table that was
in the middle of being modified by the statement which fired it.
*Action: Rewrite the trigger (or function) so it does not read that table.
When I INSERT a new contract I have to check if that client have an other contract in actual date, and if he have I must update de end date contracte to yesterday and let the new INSERT. So, how can I do to prevent the mutating table?