Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is FOR EACH ROW not needed in a BEFORE INSERT TRIGGER in Oracle?

I am new to PLSQL in Oracle. When I am learning about triggers, I have read from this source https://www.techonthenet.com/oracle/triggers/before_insert.php which says that when I create a BEFORE INSERT Trigger in Oracle, the FOR EACH ROW is NOT always needed, hence the syntax is enclosed by square brackets [ ]. I have written this simple trigger:

CREATE OR REPLACE TRIGGER enroll_time
BEFORE INSERT
ON ENROLL
FOR EACH ROW
BEGIN
:new.addtime := sysdate;
END;
/ 

If I remove the FOR EACH ROW in the above, I actually get an error:

Error report -
ORA-04082: NEW or OLD references not allowed in table level triggers
04082. 00000 -  "NEW or OLD references not allowed in table level triggers"
*Cause:    The trigger is accessing "new" or "old" values in a table trigger.
*Action:   Remove any new or old references.

From the error message, it seems like if I use :new.[column_name], then FOR EACH ROW must have to exist. Why is this? Is there any example that FOR EACH ROW is NOT needed in a BEFORE INSERT TRIGGER in Oracle?

like image 349
GreenPenguin Avatar asked Oct 24 '17 16:10

GreenPenguin


2 Answers

Is there any example that FOR EACH ROW is NOT needed in a BEFORE INSERT TRIGGER in Oracle?

Simple example of statement level trigger:

CREATE TABLE test_table(col VARCHAR2(10));

CREATE OR REPLACE TRIGGER enroll_time
BEFORE INSERT
ON ENROLL
BEGIN
   INSERT INTO test_table(col)
   SELECT 1 FROM dual;
END;
/ 

I highly recommend to read about compound trigger to understand when each part is fired.

like image 139
Lukasz Szozda Avatar answered Oct 21 '22 10:10

Lukasz Szozda


Basically, if you need to use :OLD or :NEW pseudotables, you need a row level trigger. An example of a statement level trigger would be inserting a record into a table when another table is effected.

like image 28
Karl.T Avatar answered Oct 21 '22 08:10

Karl.T