Docsity

Using Triggers in Oracle Database, Lecture notes of Database Programming

Toggle sidebar
bg1
Using Triggers
This chapter contains
About Triggers
Creating Triggers
Changing Triggers
Disabling and Enabling Triggers
About Trigger Compilation and Dependencies
Dropping Triggers
About Triggers
A trigger is a PL/SQL unit that is stored in the database and (if it is in the enabled state) automatically
executes ("fires") in response to a specified event.
A trigger has this structure:
TRIGGER trigger_name
triggering_event
[ trigger_restriction ]
BEGIN
triggered_action;
END;
The trigger_name must be unique for triggers in the schema. A trigger can have the same name as
another kind of object in the schema (for example, a table); however, Oracle recommends using a
naming convention that avoids confusion.
If the trigger is in the enabled state, the triggering_event causes the database to execute the
triggered_action if the trigger_restriction is either TRUE or omitted. The triggering_event is associated
with either a table, a view, a schema, or the database, and it is one of these:
DML statement (described in "About Data Manipulation Language (DML) Statements")
DDL statement (described in "About Data Definition Language (DDL) Statements")
Database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN)
If the trigger is in the disabled state, the triggering_event does not cause the database to execute the
triggered_action, even if the trigger_restriction is TRUE or omitted.
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Using Triggers in Oracle Database and more Lecture notes Database Programming in PDF only on Docsity!

Using Triggers

This chapter contains  About Triggers  Creating Triggers  Changing Triggers  Disabling and Enabling Triggers  About Trigger Compilation and Dependencies  Dropping Triggers About Triggers A trigger is a PL/SQL unit that is stored in the database and (if it is in the enabled state) automatically executes ("fires") in response to a specified event. A trigger has this structure: TRIGGER trigger_name triggering_event [ trigger_restriction ] BEGIN triggered_action; END; The trigger_name must be unique for triggers in the schema. A trigger can have the same name as another kind of object in the schema (for example, a table); however, Oracle recommends using a naming convention that avoids confusion. If the trigger is in the enabled state, the triggering_event causes the database to execute the triggered_action if the trigger_restriction is either TRUE or omitted. The triggering_event is associated with either a table, a view, a schema, or the database, and it is one of these: DML statement (described in "About Data Manipulation Language (DML) Statements") DDL statement (described in "About Data Definition Language (DDL) Statements") Database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN) If the trigger is in the disabled state, the triggering_event does not cause the database to execute the triggered_action, even if the trigger_restriction is TRUE or omitted.

By default, a trigger is created in the enabled state. You can disable an enabled trigger, and enable a disabled trigger. Unlike a subprogram, a trigger cannot be invoked directly. A trigger is invoked only by its triggering event, which can be caused by any user or application. You might be unaware that a trigger is executing unless it causes an error that is not handled properly. A simple trigger can fire at exactly one of these timing points: Before the triggering event executes (statement-level BEFORE trigger) After the triggering event executes (statement-level AFTER trigger) Before each row that the event affects (row-level BEFORE trigger) After each row that the event affects (row-level AFTER trigger) A compound trigger can fire at multiple timing points. For information about compound triggers, see Oracle Database PL/SQL Language Reference. An INSTEAD OF trigger is defined on a view, and its triggering event is a DML statement. Instead of executing the DML statement, Oracle Database executes the INSTEAD OF trigger. For more information, see "Creating an INSTEAD OF Trigger". A system trigger is defined on a schema or the database. A trigger defined on a schema fires for each event associated with the owner of the schema (the current user). A trigger defined on a database fires for each event associated with all users. One use of triggers is to enforce business rules that apply to all client applications. For example, suppose that data added to the EMPLOYEES table must have a certain format, and that many client applications can add data to this table. A trigger on the table can ensure the proper format of all data added to it. Because the trigger executes whenever any client adds data to the table, no client can circumvent the rules, and the code that enforces the rules can be stored and maintained only in the trigger, rather than in every client application. For other uses of triggers, see Oracle Database PL/SQL Language Reference.

Creating Triggers

To create triggers, use either the SQL Developer tool Create Trigger or the DDL statement CREATE TRIGGER. This section shows how to use both of these ways to create triggers. By default, a trigger is created in the enabled state. To create a trigger in disabled state, use the CREATE TRIGGER statement with the DISABLE clause. About OLD and NEW Pseudorecords

log_action := 'Insert'; ELSIF UPDATING THEN log_action := 'Update'; ELSIF DELETING THEN log_action := 'Delete'; ELSE DBMS_OUTPUT.PUT_LINE('This code is not reachable.'); END IF; INSERT INTO EVALUATIONS_LOG (log_date, action) VALUES (SYSDATE, log_action); END; Tutorial: Creating a Trigger that Generates a Primary Key for a Row Before It Is Inserted The sequence EVALUATIONS_SEQUENCE (created in "Tutorial: Creating a Sequence") generates primary keys for the EVALUATIONS table (created in "Creating Tables"). However, these primary keys are not inserted into the table automatically. This tutorial shows how to use the SQL Developer Create Trigger tool to create a trigger named NEW_EVALUATION_TRIGGER, which fires before a row is inserted into the EVALUATIONS table, and generates the unique number for the primary key of that row, using EVALUATIONS_SEQUENCE. The trigger fires once for each row affected by the triggering INSERT statement. NEW_EVALUATION_TRIGGER is a row-level trigger and a BEFORE trigger. To create the NEW_EVALUATION trigger: In the Connections frame, expand hr_conn. In the list of schema object types, right-click Triggers. In the list of choices, click New Trigger. In the Create Trigger window: In the Name field, type NEW_EVALUATION_TRIGGER over the default value TRIGGER1. For Base Object, select EVALUATIONS from the menu.

Move INSERT from Available Events to Selected Events. (Select INSERT and click >.) Deselect the option Statement Level. Click OK. The NEW_EVALUATION_TRIGGER pane opens, showing the CREATE TRIGGER statement that created the trigger: CREATE OR REPLACE TRIGGER NEW_EVALUATION_TRIGGER BEFORE INSERT ON EVALUATIONS FOR EACH ROW BEGIN NULL; END; The title of the NEW_EVALUATION_TRIGGER pane is in italic font, indicating that the trigger is not yet saved in the database. In the CREATE TRIGGER statement, replace NULL with this: :NEW.evaluation_id := evaluations_sequence.NEXTVAL From the File menu, select Save. Oracle Database compiles the procedure and saves it. The title of the NEW_EVALUATION_TRIGGER pane is no longer in italic font. Creating an INSTEAD OF Trigger A view presents the output of a query as a table. If you want to change a view as you would change a table, then you must create INSTEAD OF triggers. Instead of changing the view, they change the underlying tables. For example, consider the view EMP_LOCATIONS, whose NAME column is created from the LAST_NAME and FIRST_NAME columns of the EMPLOYEES table: CREATE VIEW EMP_LOCATIONS AS SELECT e.EMPLOYEE_ID,

HR_LOGON_TRIGGER adds a row to the table HR_USERS_LOG. Before someone logs off as user HR, HR_LOGOFF_TRIGGER adds a row to the table HR_USERS_LOG. HR_LOGON_TRIGGER and HR_LOGOFF_TRIGGER are system triggers. HR_LOGON_TRIGGER is an AFTER trigger and HR_LOGOFF_TRIGGER is a BEFORE trigger. To create HR_USERS_LOG, HR_LOGON_TRIGGER, and HR_LOGOFF_TRIGGER: Create the HR_USERS_LOG table: CREATE TABLE hr_users_log ( user_name VARCHAR2(30), activity VARCHAR2(20), event_date DATE ); Create hr_logon_trigger: CREATE OR REPLACE TRIGGER hr_logon_trigger AFTER LOGON ON HR.SCHEMA BEGIN INSERT INTO hr_users_log (user_name, activity, event_date) VALUES (USER, 'LOGON', SYSDATE); END; Create hr_logoff_trigger: CREATE OR REPLACE TRIGGER hr_logoff_trigger BEFORE LOGOFF ON HR.SCHEMA BEGIN INSERT INTO hr_users_log (user_name, activity, event_date) VALUES (USER, 'LOGOFF', SYSDATE);

END;

Changing Triggers

To change a trigger, use either the SQL Developer tool Edit or the DDL statement CREATE TRIGGER with the OR REPLACE clause. To change a trigger using the Edit tool: In the Connections frame, expand hr_conn. In the list of schema object types, expand Triggers. In the list of triggers, click the trigger to change. In the frame to the right of the Connections frame, the Code pane appears, showing the code that created the trigger. The Code pane is in write mode. (Clicking the pencil icon switches the mode from write mode to read only, or the reverse.) In the Code pane, change the code. The title of the pane is in italic font, indicating that the change is not yet saved in the database. From the File menu, select Save. Oracle Database compiles the trigger and saves it. The title of the pane is no longer in italic font.

Disabling and Enabling Triggers

You might need to temporarily disable triggers if they reference objects that are unavailable, or if you must upload a large amount of data without the delay that triggers cause (as in a recovery operation). After the referenced objects become available, or you have finished uploading the data, you can re- enable the triggers. This section contains: Disabling or Enabling a Single Trigger Disabling or Enabling All Triggers on a Single Table Disabling or Enabling a Single Trigger To disable or enable a single trigger, use either the Disable Trigger or Enable Trigger tool or the ALTER TRIGGER statement with the DISABLE or ENABLE clause. For example, these statements disable and enable the eval_change_trigger:

Running a CREATE TRIGGER statement compiles the trigger being created. If this compilation causes an error, then the CREATE TRIGGER statement fails. To see the compilation errors, use this statement: SELECT * FROM USER_ERRORS WHERE TYPE = 'TRIGGER'; Compiled triggers depend on the schema objects on which they are defined. For example, NEW_EVALUATION_TRIGGER depends on the EVALUATIONS table: CREATE OR REPLACE TRIGGER NEW_EVALUATION_TRIGGER BEFORE INSERT ON EVALUATIONS FOR EACH ROW BEGIN :NEW.evaluation_id := evaluations_seq.NEXTVAL; END; To see the schema objects on which triggers depend, use this statement: SELECT * FROM ALL_DEPENDENCIES WHERE TYPE = 'TRIGGER'; If an object on which a trigger depends is dropped, or changed such that there is a mismatch between the trigger and the object, then the trigger is invalidated. The next time the trigger is invoked, it is recompiled. To recompile a trigger immediately, use the ALTER TRIGGER statement with the COMPILE clause. For example: ALTER TRIGGER NEW_EVALUATION_TRIGGER COMPILE;

Dropping Triggers

You must drop a trigger before dropping the objects on which it depends. To drop a trigger, use either the SQL Developer Connections frame and Drop tool, or the DDL statement DROP TRIGGER. This statement drops the trigger EVAL_CHANGE_TRIGGER: DROP TRIGGER EVAL_CHANGE_TRIGGER; To drop a trigger using the Drop tool: In the Connections frame, expand hr_conn. In the list of schema object types, expand Triggers.

In the list of triggers, right-click the name of the trigger to drop. In the list of choices, click Drop Trigger. In the Drop window, click Apply. In the Confirmation window, click OK.