问题
When I declare a trigger in my Oracle database project, I'm getting an error, which says:
ERROR at line 1:
ORA-04091: table MIHAL277.LEAGUE_GAMES is mutating, trigger/function may not
see it
ORA-06512: at "MIHAL277.DELETE_UNUSED_GAME", line 4
ORA-04088: error during execution of trigger 'MB358996.DELETE_UNUSED_GAME'
Basically I'm creating an academic project for managing boardgame leagues. So there is a Game table and a League table. There's also a League_Games table, which indicates whether a game is available in a League (i.e if the players in the League play this game). A League can decide to stop 'owning' a game and then it's deleted from the League_Games table. But when it happens I want to run a trigger, which checks out if there are still some Leagues that use the game and if not - delete the entry for the particular game from the Game table.'
My trigger goes like this:
CREATE OR REPLACE TRIGGER delete_unused_game
BEFORE DELETE ON League_Games
FOR EACH ROW
DECLARE
deleted_game_count integer;
BEGIN
SELECT COUNT(*)
INTO deleted_game_count
FROM League_Games
WHERE Game_ID = :OLD.Game_ID;
IF deleted_game_count = 0 THEN
DELETE FROM Game
WHERE ID = :OLD.Game_ID;
END IF;
END;
/
So when I delete an entry from Leage_Games, the error appears. What is wrong with this trigger?
回答1:
You are trying to query data from the same table you are updating (well, deleting in this case ..). You can't do that, since it's "Mutating"
Read up on mutating triggers more .. Tom Kyte offers an excellent step by step here:
https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:290416059674
and another blog entry here on "The trouble with triggers":
http://www.oracle.com/technetwork/testcontent/o58asktom-101055.html
Basically, you should revisit your logic and consider doing it without using triggers ;)
来源:https://stackoverflow.com/questions/34951730/plsql-trigger-error-is-mutating-trigger-function-may-not-see-it-ora-04091