ORA-04091: table name is mutating - when trigger from child table wants to update parent table - sql

I have 2 simple tables:
CREATE TABLE ORDERS
( ORDER_KEY number(10) NOT NULL,
ORDER_NR varchar2(50) NOT NULL,
LAST_UPDATE DATE,
CONSTRAINT ORDERS_PK PRIMARY KEY (ORDER_KEY)
);
CREATE TABLE ORDER_POSITIONS
( ORDER_POS_KEY number(10) NOT NULL,
ORDER_POS_NR number(10),
ORDER_POS_DESCRIPTION varchar2(50),
ORDER_KEY NUMBER(10) NOT NULL,
CONSTRAINT ORDER_POSITIONS_PK PRIMARY KEY (ORDER_POS_KEY),
CONSTRAINT ORDERS_FK
FOREIGN KEY (ORDER_KEY)
REFERENCES ORDERS(ORDER_KEY)
ON DELETE CASCADE
);
On the table ORDER_POSITIONS I created a trigger which should update the column LAST_UPDATE whenever a position is deleted.
CREATE OR REPLACE TRIGGER TGAUDIT_ORDER_POS
AFTER DELETE
ON ORDER_POSITIONS
FOR EACH ROW
DECLARE
BEGIN
UPDATE ORDERS O SET O.LAST_UPDATE = SYSDATE WHERE O.ORDER_KEY = :OLD.ORDER_KEY;
END;
If I delete a position from the table ORDER_POSITION, everything is working fine (the column LAST_UPDATE is updated).
However, if I want to delete an order, all its positions are gonna be deleted, too (via CASCADE DELETE). At this moment also the trigger on the table ORDER_POSITIONS is being raised and it wants to update the column of the table which is currently being deleted - ORDERS. Obviously I get here the error : ORA-04091 Table ORDERS is mutating.
Is there a way to get it solved?

I solved it finally using a compound trigger:
CREATE OR REPLACE TRIGGER TGAUDIT_ORDER_POS
FOR DELETE ON ORDER_POSITIONS
COMPOUND TRIGGER
TYPE parent_key_type IS TABLE OF ORDERS.ORDER_KEY%TYPE;
parent_keys parent_key_type := parent_key_type();
AFTER EACH ROW IS BEGIN
IF DELETING THEN
BEGIN
parent_keys.extend;
parent_keys(parent_keys.last) := :old.ORDER_KEY;
END;
END IF;
END AFTER EACH ROW;
AFTER STATEMENT IS BEGIN
FOR i IN 1..parent_keys.count LOOP
UPDATE DEVART_TEST.ORDERS O SET O.LAST_UPDATE = SYSDATE WHERE O.ORDER_KEY = parent_keys(i);
END LOOP;
END AFTER STATEMENT;
END;
UPDATE: Another option would be to catch this specific exception within the regular trigger.
CREATE OR REPLACE TRIGGER TGAUDIT_ORDER_POS
AFTER DELETE
ON ORDER_POSITIONS
FOR EACH ROW
DECLARE
TABLE_MUTATING EXCEPTION;
PRAGMA EXCEPTION_INIT(TABLE_MUTATING, -4091 );
BEGIN
UPDATE ORDERS O SET O.LAST_UPDATE = SYSDATE WHERE O.ORDER_KEY = :OLD.ORDER_KEY;
EXCEPTION
WHEN TABLE_MUTATING THEN
NULL; -- suppress
END;

I would recreate the foreign-key constraint without the ON DELETE CASCADE clause and delete all order positions before deleting an order. That way you avoid the mutating table error by not having two tables mutating at the same time.

Related

Enabling and disabling a trigger inside another trigger

I got a table Location
CREATE TABLE Location (
idL INTEGER,
City VARCHAR2(15) NOT NULL,
Street VARCHAR2(35) NOT NULL,
Nation CHAR(6) NOT NULL,
CONSTRAINT PK_idL PRIMARY KEY(idL)
);
And a table Person
CREATE TABLE Person(
p_Name VARCHAR2(20) NOT NULL,
p_Surname VARCHAR2(20) NOT NULL,
idP INTEGER,
b_Date DATE NOT NULL,
id_PL INTEGER,
CONSTRAINT PK_idP PRIMARY KEY(idP),
CONSTRAINT FK_idPL FOREIGN KEY(id_PL) REFERENCES Location(idL)
);
I calculate the primary key "automatically" as it follows:
CREATE SEQUENCE seq_loc_pk
start with 1
increment by 1;
CREATE OR REPLACE TRIGGER auto_pk_loc
BEFORE INSERT ON Location
FOR EACH ROW
BEGIN
:new.idL := seq_loc_pk.nextval;
END;
/
Now I want to insert the residence for a new person (after I've created the right view of course) with an instead of trigger like this:
CREATE OR REPLACE TRIGGER newperson
INSTEAD OF INSERT ON Residence
FOR EACH ROW
DECLARE
nl Loc.idL%TYPE;
BEGIN
ALTER TRIGGER auto_pk_loc DISABLE; -- Error
nl := seq_loc_pk.nextval;
:NEW.idL := nl;
INSERT INTO Location VALUES(:NEW.City,:NEW.Street,:NEW.Nation);
INSERT INTO Patient VALUES(:NEW.P_Name,:NEW.P_Surname,:NEW.B_Date,,nl);
ALTER TRIGGER auto_pk_loc ENABLE;
END;
/
I thought about disabling and enabling the trigger auto_pk_loc so that it doesn't create extra values for no reason, but I think this is not the right way to do it? What is it though? Thanks for whoever answers.
You can do this by placing it in execute immedaite:
BEGIN
execute immedidate 'ALTER TRIGGER auto_pk_loc DISABLE';
nl := seq_loc_pk.nextval;
:NEW.idL := nl;
INSERT INTO Location VALUES(:NEW.City,:NEW.Street,:NEW.Nation);
INSERT INTO Patient VALUES(:NEW.P_Name,:NEW.P_Surname,:NEW.B_Date,,nl);
execute immedidate 'ALTER TRIGGER auto_pk_loc ENABLE';
END;
/
But this will cause you all sorts of issues; DDL commits so you'll have to make this an autonomous transaction and you'll hit concurrency problems. This is best avoided.
A better method is to use the returning clause to fetch the value you just inserted:
BEGIN
INSERT INTO Location VALUES(:NEW.City,:NEW.Street,:NEW.Nation)
returning idl into nl;
INSERT INTO Patient VALUES(:NEW.P_Name,:NEW.P_Surname,:NEW.B_Date,nl);
END;
/
Though as #astentx noted, you probably want to use merge to avoid having duplicate locations. This doesn't support returing, so you'll have to use some combination of insert+update instead.
Finally - assuming you're on 12c or higher - it's better to use an identity column or sequence default to auto-generate the location IDs over a trigger.

How to avoid mutating table in a trigger when working with nested table, and do an update into another table?

I have a code that uses a trigger to do an update into a table after a dml insert has been done, but i need the information inside an atributte that is a nested table, and with that information do the update, but my code throws a mutating table error, and i want to know what is it that i am doing wrong, this is the code with the tables, types and trigger involved.
----create the type tipo_detalle---------------
CREATE OR REPLACE TYPE tipo_detalle AS OBJECT(
codigo NUMBER(1),
cantidad NUMBER(2)
);
/
-----declare the nested table with type tipo_detalle---
CREATE OR REPLACE TYPE detalle_anidado AS TABLE OF tipo_detalle;
/
---------create the table pedido------------------------
CREATE TABLE pedido(
cod_bodega REFERENCES bodega,
dia NUMBER(8),
columna_detalle detalle_anidado,
PRIMARY KEY(cod_bodega,dia)
)
NESTED TABLE columna_detalle STORE AS columna_detalle_anidada
((PRIMARY KEY(NESTED_TABLE_ID,codigo)));
---table where i am going to insert after insert in pedido----
CREATE TABLE inventario(
cod_bodega REFERENCES bodega,
cod_producto REFERENCES producto,
existencia NUMBER(8),
PRIMARY KEY(cod_bodega,cod_producto)
);
------ trigger to do an insert into inventario-----------
CREATE OR REPLACE TRIGGER triggers_de_pedido
FOR INSERT OR UPDATE OR DELETE ON pedido
COMPOUND TRIGGER
contador NUMBER(8);
fila pedido.columna_detalle%TYPE;
cod_producto_ NUMBER(1);
cantidad_ NUMBER(2);
indice NUMBER(4);
AFTER EACH ROW IS
BEGIN
IF INSERTING THEN
SELECT columna_detalle INTO fila FROM pedido WHERE
cod_bodega=:NEW.cod_bodega AND dia=:NEW.dia;
indice:=fila.FIRST;
WHILE indice IS NOT NULL LOOP
cod_producto_:=fila(indice).codigo;
cantidad_:=fila(indice).cantidad;
UPDATE inventario SET existencia=existencia-cantidad_
WHERE cod_bodega=:NEW.cod_bodega AND cod_producto=cod_producto_;
indice:=fila.NEXT(indice);
END LOOP;
END IF;
END AFTER EACH ROW;
END triggers_de_pedido;
/
The error is raised because you are selecting from the Trigger owner(the table pedido) inside the Trigger.
Change this select statement
SELECT columna_detalle INTO fila FROM pedido WHERE ...
to
IF INSERTING THEN
fila := :NEW.columna_detalle;

Oracle - Using a trigger to delete a row

When an insert is made to Condo_assign I am using multiple triggers to add entries to a reserveError table to indicate what the error was. After they are logged in reserveError I am now attempting to use another trigger to delete the record from condo_assign that caused the problem. Basically, the erroneous insert should be logged in ReserveError and Deleted from Condo_assign. The problem is that while my delete trigger compiles and causes no problems, it doesn't appear to do anything. when I select * from condo_assign the erroneous entries are still there.
Condo_Assign table:
CREATE TABLE Condo_Assign (
MID INT
, RID VARCHAR2(3)
, CONSTRAINT Condo_Assign Primary Key (MID,RID)
, CONSTRAINT MID_Assign_FK Foreign Key (MID) references SkiClub (MID)
, CONSTRAINT RID_Assign_FK Foreign Key (RID) references Condo_Reservation (RID)
);
reserveError Table:
CREATE TABLE ReserveError (
Err INT PRIMARY KEY
, MID INT
, RID VARCHAR2(3)
, errorDate DATE
, errorCode VARCHAR2(6)
, errorMsg VARCHAR2(60)
, CONSTRAINT Error_MID_FK FOREIGN KEY (MID) REFERENCES SkiClub
, CONSTRAINT Error_RID_FK FOREIGN KEY (RID) REFERENCES Condo_Reservation
);
Procedure that causes trigger to fire:
CREATE OR REPLACE Procedure addCondo_Assign
(
inMID in Condo_Assign.MID%type
, inRID in Condo_Assign.RID%type
, inPaymentDate in Payment.PaymentDate%type
, inPayment in Payment.Payment%type
)
is
begin
insert into Condo_Assign (MID,RID) values (inMid,inRid);
IF inPayment >= 50 then
insert into Payment (MID,RID,PaymentDate,Payment) values (inMID,inRID,inPaymentDate,inPayment);
ELSE
raise_application_error(-20088,'Deposit less than 50');
end if;
exception
when others then
raise_application_error(-20005,'Cannot add to entry to Condo_Assign Table.');
end addCondo_Assign;
/
Trigger that writes to ReserveError table
-- Trigger to prevent gender mismatchs in room assignment
CREATE OR REPLACE TRIGGER Gender_Assign_Trigger
BEFORE INSERT ON Condo_Assign
FOR EACH ROW
DECLARE
Room_Gender Char(1);
Guest_Gender Char(1);
BEGIN
SELECT Gender
INTO Room_Gender
From Condo_Reservation
WHERE RID = :new.RID;
SELECT Gender
INTO Guest_Gender
FROM SkiClub
WHERE MID = :new.MID;
IF Room_Gender = 'M' AND Guest_Gender = 'F' THEN
addReserveError(:new.MID,:new.RID,SYSDATE,'g00001','Female guest assigned to male room');
ELSIF Room_Gender = 'F' AND Guest_Gender = 'M' THEN
addReserveError(:new.MID,:new.RID,SYSDATE,'g00002','Male guest assigned to female room');
END IF;
END Gender_Assign_Trigger;
/
Trigger that should delete entry from condo_assign:
CREATE OR REPLACE TRIGGER Remove_errors_trigger
after Insert on ReserveError
FOR EACH ROW
BEGIN
DELETE FROM Condo_Assign
WHERE MID = :new.MID and RID = :new.RID;
END remove_errors_trigger;
/
The entire process is started in a before insert trigger.
The code that tries to delete the record won't delete anything because the record has not been inserted yet. There is nothing to delete at the time the delete code is being fired.
Usually checks in triggers prevent the insertion of incorrect data throwing an exception. The code inserting the data will have to handle the exception.
But you already have a procedure that handles the insert. It even performs a check on the deposit. Why not handle the gender check there?

PL/SQL: NO DATA FOUND while updating another table based on conditions

So I have a column on my PAYMENT table that is called Status.. It has a foreign key of another table called reservation with Reservation_ID. The Reservation Table also has a status column and it will only get updated when there is a value in the status column of payment table. So If my status field in payment table has the value "Confirmed", the value for that particular Reservation_ID is supposed to turn to 1.. Otherwise 22. This is how I made the trigger:
CREATE OR REPLACE TRIGGER stats BEFORE INSERT OR DELETE OR UPDATE ON PAYMENT FOR EACH ROW
DECLARE
V_STATUS VARCHAR2(20);
BEGIN
SELECT Status INTO V_STATUS FROM PAYMENT INNER JOIN RESERVATION ON PAYMENT.Reservation_ID=RESERVATION.Reservation_ID WHERE PAYMENT.Reservation_ID=:NEW.Reservation_ID;
IF INSERTING AND V_STATUS='CONFIRMED' THEN
UPDATE RESERVATION SET status=1 WHERE Reservation_ID=:new.Reservation_ID;
ELSIF UPDATING AND V_STATUS='CONFIRMED' THEN
UPDATE RESERVATION SET status=1 WHERE Reservation_ID=:new.Reservation_ID;
ELSE
UPDATE RESERVATION SET status=22 WHERE Reservation_ID=:new.Reservation_ID;
END IF;
END;
So the trigger basically gets compiled but when I try inserting values inside Payment Table, I get the following error:
Error report -
ORA-01403: no data found
ORA-06512: at "ME.STATS", line 4
ORA-04088: error during execution of trigger 'ME.STATS'
create statments for both tables:
CREATE TABLE RESERVATION(RESERVATION_id NUMBER(10) NOT NULL, MEMBER_ID NUMBER(10) CONSTRAINT RE_MEM_fk REFERENCES MEMBER(MEMBER_ID) ON DELETE SET NULL,status NUMBER(10) CONSTRAINT RES_status_fk REFERENCES STATUS(RESERVATION_status_id) ON DELETE SET NULL, CONSTRAINT PK_BOOK PRIMARY KEY(RESERVATION_id));
CREATE TABLE PAYMENT(Payment_ID NUMBER(10) NOT NULL ,RESERVATION_id NUMBER(10) CONSTRAINT Pay_RES_fk REFERENCES RESERVATION(RESERVATION_id) ON DELETE SET NULL, TicketPrice NUMBER(10), ExtraFaciliFees Number(10),TOTAL_AMOUNT Number(10), PromotionalCode VARCHAR2(10), CONSTRAINT PK_PAY PRIMARY KEY(Payment_ID));
First :
CREATE TABLE RESERVATION(
Status NUMBER(10));
SELECT Status INTO V_STATUS
IF INSERTING AND V_STATUS='CONFIRMED'
Could you explain me how you expect a NUMBER to match a string ?
Next (from http://www.dba-oracle.com/sf_ora_01403_no_data_found.htm )
SELECT INTO clauses are standard SQL queries which pull a row or set
of columns from a database, and put the retrieved data into variables
which have been predefined.
If the SELECT INTO statement doesn't return at least on e row,
ORA-01403 is thrown.
So this :
SELECT
Status INTO V_STATUS
FROM PAYMENT p
INNER JOIN RESERVATION r
ON p.Reservation_ID = r.Reservation_ID
WHERE p.Reservation_ID = :NEW.Reservation_ID;
Is likely to output no row at all...
Agree with #Blag, below statement is giving the no data found exception.
In general if you want to know the exact line number the error is pointing to you can refer to the object via DBA_SOURCE or ALL_SOURCES.
SELECT
Status INTO V_STATUS
FROM PAYMENT p
INNER JOIN RESERVATION r
ON p.Reservation_ID = r.Reservation_ID
WHERE p.Reservation_ID = :NEW.Reservation_ID;

Use trigger to determine to implement insert or not

I am a beginner of SQL and Oracle database, and I need a little help about trigger. Here is the question:
I need to create a trigger that before insert a row into table Room, it will check this new row's hotel_id to see if it exists in another table Hotel. If the new hotel_id exists, then do the insert; if not, cancel this insert.
My code:
CREATE OR REPLACE TRIGGER TRIGGER1
BEFORE INSERT ON ROOM
FOR EACH ROW
BEGIN
if (:new.hotel_id in (select hotel_id from hotel)) then
--execute the insert;
else
--cancel the insert;
end if;
END;
I'm not sure that SQL has syntax that can be used to continue or cancel an operation. If there is, please teach me or attach the link related to it.
Correct way of doing this is using foreign key constraints.
You can define/alter your room table to refer it in the hotel_id column.
CREATE TABLE:
create table room (
. . .,
hotel_id int not null,
constraint fk_hotel_id foreign key (hotel_id)
references hotel(hotel_id)
);
ALTER TABLE:
alter table room
add constraint fk_hotel_id foreign key (hotel_id)
references hotel(hotel_id);
If the two table exists in different databases, then you can use trigger.
You can use raise_application_error proc to abort the execution and throw error.
create or replace trigger trigger1
before insert or update
on room for each row
declare
n integer := 0;
begin
select count(*) into n
from hotel
where hotel_id = :new.hotel_id;
if n = 0 then
raise_application_error(-20001, 'Hotel ID doesn't exist');
end if;
end;
As GurV said, foreign keys are more appropriate way for doing this
Though, here is trigger way:
CREATE OR REPLACE TRIGGER TRIGGER1
BEFORE INSERT ON ROOM
FOR EACH ROW
declare myvar INT;
BEGIN
SELECT 1 INTO myvar FROM Hotel WHERE hotel_id = :NEW.hotel_id FETCH NEXT 1 ROW ONLY;
exception
when no_data_found then
RAISE_APPLICATION_ERROR (-20000, 'some_error_message');
END;