Lecture 3.1.3 - Introduction To Triggers Lecture 3.1.4 - Implementation of Triggers
Lecture 3.1.3 - Introduction To Triggers Lecture 3.1.4 - Implementation of Triggers
Lecture 3.1.3 - Introduction To Triggers Lecture 3.1.4 - Implementation of Triggers
2
COURSE OUTCOMES
3
Triggers
• Triggers in oracle are blocks of PL/SQL code which oracle
engine can execute automatically based on some action or
event.
• These events can be:
DDL statements (CREATE, ALTER, DROP, TRUNCATE)
DML statements (INSERT, SELECT, UPDATE, DELETE)
Database operation like connecting or disconnecting to oracle (LOGON,
LOGOFF, SHUTDOWN)
Parts of a Trigger
Whenever a trigger is created, it contains the following
three sequential parts:
2. Trigger Restriction
3. Trigger Action
Types of Triggers
2. AFTER TRIGGER
• It fires after executing DML statement.
Syntax for creating Triggers
CREATE OR REPLACE TRIGGER <trigger_name>
BEFORE/AFTER/INSTEAD OF
INSERT/DELETE/UPDATE ON <table_name>
REFERENCING (OLD AS O, NEW AS N)
FOR EACH ROW WHEN (test_condition)
DECLARE
-- Variable declaration;
BEGIN
-- Executable statements;
EXCEPTION
-- Error handling statements;
END <trigger_name>;
Explanation
• CREATE OR REPLACE TRIGGER is a keyword used to create a trigger
and <trigger_name> is user-defined where a trigger can be given a name.
• BEFORE/AFTER/INSTEAD OF specify the timing of the trigger's occurance. INSTEAD
OF is used when a view is created.
• INSERT/UPDATE/DELETE specify the DML statement.
• <table_name> specify the name of the table on which DML statement is to be applied.
• REFERENCING is a keyword used to provide reference to old and new values for DML
statements.
• FOR EACH ROW is the clause used to specify row level tigger.
• WHEN is a clause used to specify condition to be applied and is only applicable for row-
level trigger.
• DECLARE, BEGIN, EXCEPTION, END are the different sections of PL/SQL code block
containing variable declaration, executable statements, error handling statements and
marking end of PL/SQL block respectively where DECLARE and EXCEPTION part are
optional.
Example Programs!!! Before Insert
1. CREATE TABLE TEST(num number)
2. CREATE OR REPLACE TRIGGER mytrig1 BEFORE INSERT ON Test FOR
EACH ROW
BEGIN
DBMS_OUTPUT.PUT_LINE('The control is inside MyTrig1');
DBMS_OUTPUT.PUT_LINE('Before insert of '||:NEW.num);
END;
3. INSERT INTO TEST VALUES(1)
Output:
Before insert of 1
1 row(s) inserted.
Example Programs!!! After insert Trigger
(a) CREATE OR REPLACE TRIGGER mytrig2
AFTER INSERT ON Test FOR EACH ROW
BEGIN
DBMS_OUTPUT.PUT_LINE('The control is inside MyTrig2');
DBMS_OUTPUT.PUT_LINE(‘After insert of '||:NEW.num);
END;
/
(b) INSERT INTO Test VALUES(2);
Another Example!!!
• CREATE OR REPLACE TRIGGER test_insert_before BEFORE
INSERT ON Test FOR EACH ROW
BEGIN
If :NEW.num>0 then
DBMS_OUTPUT.PUT_LINE('This is +ve No. '||:NEW.num);
else
DBMS_OUTPUT.PUT_LINE('This is -ve No. '||:NEW.num);
end if;
END;
• Output: INSERT INTO TEST VALUES(-5)
This is –ve no…
Defining Your Own Error Messages:
RAISE_APPLICATION_ERROR()
• The procedure RAISE_APPLICATION_ERROR lets you issue user-
defined ORA- error messages from stored subprograms. That way, you
can report errors to your application and avoid returning unhandled
exceptions.
• To call RAISE_APPLICATION_ERROR, use the following Syntax
RAISE_APPLICATION_ERROR(error_number, message[, {TRUE | FALSE}]);
Where,
• error_number is a negative integer in the range -20000 .. -20999
• message is a character string up to 2048 bytes long.
Example Program!!!
CREATE OR REPLACE TRIGGER mytrig1 BEFORE INSERT ON test FOR
EACH ROW
BEGIN
IF :New.num > 0 THEN
DBMS_OUTPUT.PUT_LINE('This is my trigger-1, which is executed before
inserting value '||:NEW.num||' Into the table');
ELSE
RAISE_APPLICATION_ERROR(-20001 ,'Negative Numbers are not allows, pls
insert +ve values....');
END IF;
END;
Example…
CREATE OR REPLACE TRIGGER CheckAge
BEFORE INSERT OR UPDATE ON student FOR EACH ROW
BEGIN
IF :new.Age > 30 THEN
RAISE_APPLICATION_ERROR(-20001, 'Age should not be greater than 30');
END IF;
END;
END;
Example:- Statement Trigger
CREATE OR REPLACE TRIGGER mytrig4 BEFORE DELETE OR INSERT OR UPDATE
ON emp
BEGIN
IF (TO_CHAR(SYSDATE, 'day') IN ('sat', 'sun')) OR (TO_CHAR(SYSDATE,'hh:mi') NOT
BETWEEN '08:30' AND '18:30') THEN
RAISE_APPLICATION_ERROR(-20500, 'table is secured');
END IF;
END;
/*The above example shows a trigger that limits the DML actions to the employee
table to weekdays from 8.30am to 6.30pm. If a user tries to insert/update/delete a
row in the EMPLOYEE table, a warning message will be prompted.*/
Simple Log of Ex_Stu
CREATE OR REPLACE TRIGGER mytrig2 AFTER DELETE ON stu
FOR EACH ROW
BEGIN
INSERT INTO ex_stu VALUES (:old.rn, :old.name,:old.age, sysdate);
END;
CREATE OR REPLACE TRIGGER mytrig5
AFTER DELETE OR INSERT OR UPDATE ON employee FOR EACH ROW
BEGIN
IF DELETING THEN
INSERT INTO xemployee (emp_ssn, emp_last_name,emp_first_name, deldate)
VALUES (:old.emp_ssn, :old.emp_last_name,:old.emp_first_name, sysdate);
ELSIF INSERTING THEN
INSERT INTO nemployee (emp_ssn, emp_last_name,emp_first_name, adddate)
VALUES (:new.emp_ssn, :new.emp_last_name,:new.emp_first_name, sysdate);
ELSE
INSERT INTO uemployee (emp_ssn, emp_address, up_date)
VALUES (:old.emp_ssn, :new.emp_address, sysdate);
END IF;
END;
Check the log now,
• SQL> DELETE FROM employee WHERE ename = 'Joshi';
1 row deleted.
• SQL> SELECT * FROM xemployee;
Enabling or Disabling the Triggers
• SQL>ALTER TRIGGER trigger_name DISABLE;
• SQL>ALTER TABLE table_name DISABLE ALL TRIGGERS;
All triggers can be enabled for a specific table by using the following
command
• SQL> ALTER TABLE table_name ENABLE ALL TRIGGERS;
• SQL> DROP TRIGGER trigger_name
Uses of Triggers
• Maintaining complex constraints
• Recording the changes made on the table.
• Automatically generating primary key values.
• Prevent invalid transactions to occur.
• Granting authorization and providing security to
database.
• Enforcing referential integrity.
• Audit data modification
• Log events transparently
References
• RamezElmasri and Shamkant B. Navathe, “Fundamentals of Database System”, The
Benjamin / Cummings Publishing Co.
• Korth and Silberschatz Abraham, “Database System Concepts”, McGraw Hall.
• C.J.Date, “An Introduction to Database Systems”, Addison Wesley.
• Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical Approach
to Design, Implementation and Management”, 5/E, University of Paisley, Addison-
Wesley.
26
References
• https://
docs.oracle.com/database/121/LNPLS/packages.htm
27
THANK YOU
For queries
Email: [email protected]
28