A Trigger is...

A block of PL/SQL (or Java, or C) code that executes, or "fires",
when a particular event occurs within the database.

Events include:



 

Triggers are useful for...

 

Types of Triggers...






 

Examples:
User logon / logoff
  1. Log all sessions (to internal table)
  2. Add access control by user and time of day with autonomous txn
  3. Set session attributes (NLS date format) with file debug
Database startup / shutdown, server error
  1. Log all startups and shutdowns
  2. Preload code table into KEEP buffer and pin a PL/SQL package in shared pool
  3. Log information about server errors
DDL triggers
  1. Prevent any DDL in the database, except certain users and log their changes
  2. Prevent / log specific DDL on specific schema
DML triggers
  1. Multi-function (insert/update/delete) with simple debug
  2. Audit updates with pipe debug and poor man's pipe listener
INSTEAD OF triger
  1. Update of department summary view
 

 
Firing Order
all before statement triggers
loop for each row...
all before row triggers
lock row, check integrity, apply change
all after row triggers
deferred integrity constraint checking
all after statement triggers
  


Enabling / Disabling / Compiling
SET PAGESIZE 0
SET FEEDBACK OFF
SET ECHO OFF
SPOOL TEMP.SQL
SELECT 'ALTER TRIGGER ' || TRIGGER_NAME || ' DISABLE;'
      FROM USER_TRIGGERS
      WHERE TABLE_NAME IN ( 'EMP' , 'DEP' , 'REG' );
SPOOL OFF
@TEMP.SQL
  


Viewing Triggers
Source code for a trigger
 
SET PAGESIZE 0
SET LONG 32000
SELECT TRIGGER_BODY, ...
   FROM USER | ALL | DBA_TRIGGERS
   WHERE TRIGGER_NAME = ... ;

SELECT LINE, TEXT
   FROM USER | ALL | DBA_SOURCE
   WHERE TYPE = 'TRIGGER' AND NAME = ...;

All triggers for a given table
 
SELECT OWNER, TRIGGER_NAME, ...
   FROM USER | ALL | DBA_TRIGGERS
   WHERE TABLE_NAME = ... '
  


Tricks & Traps
Transactions
Size & Structure
Failure
Debugging
Trigger Condition - WHEN Clause
Privileges
Triggers may not fire
Many other caveats and restrictions exist, see the Documentation!
  


Loading Data
SQL*Loader
-  Insert triggers fire during conventional path loads, but not direct path

Import
By default triggers do not fire
IGNORE=Y causes existing triggers to fire

Data Pump
Should use External Table method over Direct Path if active triggers exist

Data conversion / loading
Create a unique user to run conversion / loading programs
Code user-specific logic into triggers to handle conversion / loading
 
IF (ora_login_user != 'DATACONV') THEN
   [usual trigger logic]
ELSE
   [special data conversion logic, if any]
END IF;
  


Oracle Documentation References

Database Concepts
ch 22, Triggers

Database Application Developer's Guide - Fundamentals
ch 9, Using Triggers
ch 10, Working With System Events

Database SQL Reference
ch 16, Create Trigger
ch 13, Alter Trigger
ch 18, Drop Trigger

Copyright (c) 2004, Caleb.com
Contact: Caleb Small, 250-598-5511, caleb@caleb.com