Lecture 3.1.3 - Introduction To Triggers Lecture 3.1.4 - Implementation of Triggers

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 28

APEX INSTITUTE OF TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Database Management System (22CSH-243)


• Faculty: Ms. Shaveta Jain (13464)

Triggers DISCOVER . LEARN . EMPOWER


1
DBMS: Course Objectives
COURSE OBJECTIVES
The Course aims to:
• Understand database system concepts and design databases for different applications
and to acquire the knowledge on DBMS and RDBMS.
• Implement and understand different types of DDL, DML and DCL statements.
• Understand transaction concepts related to databases and recovery/backup
techniques required for the proper storage of data.

2
COURSE OUTCOMES

On completion of this course, the students shall be able to:-

CO4 Implement the package, procedures and triggers

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:

1. Triggering Event or Statement

2. Trigger Restriction

3. Trigger Action
Types of Triggers

Triggers can be classified into three categories:


1. Level Triggers
2. Event Triggers
3. Timing Triggers

• which are further divided into different parts.


1. Level Triggers
There are 2 different types of level triggers, they are:
1. ROW LEVEL TRIGGERS
• It fires for every record that got affected with the execution of DML
statements like INSERT, UPDATE, DELETE etc.
• It always use a FOR EACH ROW clause in a triggering statement.
2. STATEMENT LEVEL TRIGGERS
• It fires once for each statement that is executed.
2. Event Triggers
There are 3 different types of event triggers, they are:
1. DDL EVENT TRIGGER
• It fires with the execution of every DDL statement(CREATE, ALTER, DROP,
TRUNCATE).
2. DML EVENT TRIGGER
• It fires with the execution of every DML statement(INSERT, UPDATE,
DELETE).
3. DATABASE EVENT TRIGGER
• It fires with the execution of every database operation which can be
LOGON, LOGOFF, SHUTDOWN, SERVERERROR etc.
3. Timing Triggers
There are 2 different types of timing triggers, they are:
1. BEFORE TRIGGER
• It fires before executing DML statement.
• Triggering statement may or may not executed depending upon the before
condition block.

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;

• Student(rn, name, age)


Let's take a few examples and try to understand this,
Example 1:
• INSERT into STUDENT values(16, 'Saina', 32);
• Output: Age should not be greater than 30
Example 2:
• INSERT into STUDENT values(17, 'Anna', 22);
• Output: 1 row created
Example 3:
• UPDATE STUDENT set age=31 where ROLLNO=12;
• Output: Age should not be greater than 30
Example 4:
• UPDATE STUDENT set age=23 where ROLLNO=12;
• Output: 1 row updated.
Example:- Statement Trigger
CREATE OR REPLACE TRIGGER mytrig1 BEFORE DELETE OR INSERT OR UPDATE
ON emp
BEGIN
RAISE_APPLICATION_ERROR(-20500, 'table is secured');

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;

To enable a trigger, which is disabled, we can use the following syntax:


• SQL>ALTER TABLE table_name ENABLE trigger_name;

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

You might also like