November 24, 2009

Table Mutating Trigger

When a Trigger is created on a table and the trigger code is performing the read operation on the same table, then the mutating happens.

CREATE TRIGGER sample_trigger
AFTER INSERT
ON sample_table
FOR EACH ROW
local_variable NUMBER;
BEGIN
IF INSERTING
THEN
SELECT sample_column
INTO local_variable
FROM sample_table;
.
.
.

END IF;
END sample_trigger;

To resolve this, we need to store the required values in global variables when row level trigger is fired and create a statement level trigger which uses this global variable.

CREATE PACKAGE sample_package AS
global_variable NUMBER;
END sample_package;

--row level trigger
CREATE TRIGGER sample_trigger_1
AFTER INSERT
ON sample_table
FOR EACH ROW
BEGIN
IF INSERTING
THEN
global_variable := :NEW.sample_column;
END IF;
END sample_trigger_1;

--statement level trigger
CREATE TRIGGER sample_trigger_2
AFTER INSERT
ON sample_table
BEGIN
IF INSERTING
THEN
local_variable := global_variable;
.
.
.

END IF;
END sample_trigger_2;

Disadvantage: It will be useful only when COMMIT happens for each and every row separately. It will not be useful when COMMIT happens after multiple updates. The second trigger fires only after COMMIT and the required operation happens only for the last row.

No comments:

Post a Comment