0% found this document useful (0 votes)
56 views41 pages

Lecture 3.3 - Introduction To Triggers Lecture 3.4 - Implementation of Triggers

The document discusses database triggers in Oracle. It defines what triggers are and their main components. It describes the different types of triggers - row level triggers, statement level triggers, DDL triggers, DML triggers, and database triggers. It also covers trigger timing, syntax for creating triggers, example programs, defining error messages, using triggers for logging, enabling/disabling triggers, and uses of triggers. Packages in PL/SQL are also introduced, including their components and how to create packages.

Uploaded by

bobbinpreet kaur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views41 pages

Lecture 3.3 - Introduction To Triggers Lecture 3.4 - Implementation of Triggers

The document discusses database triggers in Oracle. It defines what triggers are and their main components. It describes the different types of triggers - row level triggers, statement level triggers, DDL triggers, DML triggers, and database triggers. It also covers trigger timing, syntax for creating triggers, example programs, defining error messages, using triggers for logging, enabling/disabling triggers, and uses of triggers. Packages in PL/SQL are also introduced, including their components and how to create packages.

Uploaded by

bobbinpreet kaur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

APEX INSTITUTE OF TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Database Management System (CST-227)


Faculty: Mr. Pramod Vishwakarma (E9758)

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.

By: Pramod Vishwakarma (E9758) 2


COURSE OUTCOMES

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


Understand the database concept, system architecture and role of database
CO1
administrator
CO2 Design database for an organization using relational model
Apply relational algebra and relational calculus to query the database of
CO3
organization
CO4 Implement the package, procedures and triggers
CO5 Understand the concept of transaction processing and concurrency  control

By: Pramod Vishwakarma (E9758) 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 allowed, please
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
Packages in PL/SQL
• A package is a way of logically storing the subprograms
like procedure, function, exception or cursor into a single
common unit.

• A package can be defined as an oracle object that is


compiled and stored in the database.

• Once it is compiled and stored in the database it can be


used by all the users of database who have executable
permissions on Oracle database.
Components of Package

Package has two basic components:


• Specification: It is the declaration section of a
Package
• Body: It is the definition section of a Package.
Creating Package
STEP 1: Package specification or declaration,
• It mainly comprises of the following:
• Package Name.
• Variable/constant/cursor/procedure/function/
exception declaration.
• This declaration is global to the package.
Syntax: Package specification or declaration
CREATE OR REPLACE PACKAGE <package_name> IS/AS
FUNCTION <function_name> (<list of arguments>) RETURN
<datatype>;
PROCEDURE <procedure_name> (<list of arguments>);
-- code statements
END <package_name>;
STEP 2: Package Body

It mainly comprises of the following:


• It contains the definition of procedure, function or
cursor that is declared in the package specification.
• It contains the subprogram bodies containing
executable statements for which package has been
created
Here is the syntax:
Syntax- Package Body
CREATE OR REPLACE PACKAGE BODY <package_name> IS/AS
FUNCTION <function_name> (<list of arguments>) RETURN <datatype>IS/AS
-- local variable declaration;
BEGIN
-- executable statements;
EXCEPTION
-- error handling statements;
END <function_name>;

PROCEDURE <procedure_name> (<list of arguments>)IS/AS


-- local variable declaration;
BEGIN
-- executable statements;
EXCEPTION
-- error handling statements;
END <procedure_name>;
END <package_name>;
Where,
• CREATE OR REPLACE PACKAGE BODY are keywords used to create the
package with a body.
• FUNCTION and PROCEDURE are keywords used to define function and
procedure while creating package.
• <package_name>, <function_name>, <procedure_name> are user-defined.
• IS/AS are keywords used to define the body of package, function and
procedure.
• RETURN is a keyword specifying value returned by the function defined.
• 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.
Referring A Package Object
• Note: Creating a package only defines it, to use it we must
refer it using the package object.

• Syntax: Following is the syntax for referring a package


object:
Packagename.objectname;
• The Object can be a function, procedure, cursor, exception that
has been declared in the package specification and defined in
the package body and to access their executable statements
above syntax is used.
Example: PL/SQL code for package specification:
CREATE OR REPLACE PACKAGE pkg_student IS
PROCEDURE updateRecord(sno student.rollno%type);
FUNCTION deleteRecord(snm student.sname%type)
RETURN boolean;
END pkg_Emp;

Output: Package is created.


PL/SQL code for package body:
CREATE OR REPLACE PACKAGE BODY pkg_student IS
PROCEDURE updateRecord(sno student.rollno%type) IS
BEGIN
Update student set age=23 where rollno=sno;
IF SQL%FOUND THEN
dbms_output.put_line('RECORD UPDATED');
ELSE
dbms_output.put_line('RECORD NOT FOUND');
END IF;
END updateRecord;
FUNCTION deleteRecord(snm student.sname%type) RETURN boolean IS
BEGIN
Delete from student where sname=snm;
RETURN SQL%FOUND;
END deleteRecord;
END pkg_student;
Calling the Procedure and Function
set serveroutput on;
DECLARE
sno student.rollno%type;
s_age student.age%type;
snm student.sname%type;
BEGIN
sno := &sno;
snm := &snm
pkg_student.updateRecord(sno);
IF pkg_student.deleteRecord(snm) THEN
dbms_output.put_line('RECORD DELETED');
ELSE
dbms_output.put_line('RECORD NOT FOUND');
END IF;
END;
Error!!!
• Note: If the package specification or package body has
been created with compilation errors then a following
warning message is displayed on the screen:
• WARNING: Package Body created with compilation errors.
• In that case, the errors can be seen by executing following
statement:
SHOW ERRORS;
Benefits of using Package

Following are some of the benefits of packages in


PL/SQL:
• REUSABILITY

• OVERLOADING

• CREATING MODULES

• IMPROVES PERFORMANCE

• GLOBAL DECLARATION
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.

By: Pramod Vishwakarma (E9758) 39


References
• https://docs.oracle.com/database/121/LNPLS/packages.h
tm

40
THANK YOU

For queries
Email: [email protected]
41

You might also like