SlideShare a Scribd company logo
2
Most read
3
Most read
4
Most read
1 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
UNIT-V: PL/SQL, Cursor and Trigger
Introduction to PL/SQL:
 SQL is the natural language of Oracle.
 Although SQL is very powerful tool, it suffers from following some major
disadvantages.
 The disadvantages of SQL are:
o SQL does not have programming techniques such as looping and
branching.
o SQL statements are passed to Oracle Engine one at a time.
o SQL does not have facility to define programmer defined error
messages.
Because of these disadvantages we cannot use SQL as conventional
programming language. Hence, Oracle provides a fully structured language
called, PL/SQL.
 The PL/SQL programming language was developed by Oracle Corporation in
the late 1980s as procedural extension language for SQL.
 Advantages of PL/SQL:
o Tight Integration with SQL:
 PL/SQL lets you use all SQL data manipulation, cursor control,
and transaction control statements, and all SQL functions,
operators.
 PL/SQL fully supports SQL data types.
o High Performance:
 PL/SQL lets you to send block of statements as a unit to Oracle
engine rather sending single statement like SQL.
2 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
o High Productivity:
 PL/SQL lets you write compact code for manipulating data just
as a scripting language like PERL that can read, transform, and
write data in files.
o Portability:
 You can run PL/SQL applications on any operating system and
platform where Oracle Database runs.
o Support for Programming Techniques:
 We can implement decision making and looping techniques in
PL/SQL block like in other standard programming languages.
o Reusability:
 PL/SQL allow to create stored subprograms and let them use any
number of applications without maintaining duplicate copies of
subprograms.
o Support for Object Oriented Programming:
 PL/SQL supports object-oriented programming with "Abstract
Data Types".
o Support for developing Web application:
 PL/SQL lets you create applications that generate web pages
directly from the database, allowing you to make your database
available on the Web and make back-office data accessible on the
intranet.
3 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
PL/SQL Block Structure:
Fig. Generic structure of PL/SQL Block
 A generic PL/SQL block is consisting following FOUR sections:
1. DECLARE section
2. BEGIN section
3. EXCEPTION section
4. END section
1. Declare Section:
It contains declaration of memory variables used later in BEGIN
section.
2. Begin Section:
It contains SQL executable statements for manipulating table data as
well as procedural statements. The executable statements should be present in
BEGIN....END block.
3. Exception Section:
It is optional section. It contains code for handling errors that
generate in above PL/SQL block.
4. END Section:
It indicates end of PL/SQL block. It should be terminated with
semicolon.
DECLARE
BEGIN
[EXCEPTION]
END;
Declarations of variables, constants cursors, etc.
SQL executable statements
PL/SQL executable statements
SQL or PL/SQL code to handle user defined errors during
the execution of PL/SQL block
4 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
For example,
Output:
Enter value for x : 10
Entered number is= 10
DECLARE
x number(3); -- Variable declaration
BEGIN
x:= &x; -- Reading value for ‘x’ from keyboard
dbms_output.put_line(‘Entered number is=‘ || x);
END;
5 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
:Variable and Constants:
 Variable is nothing but name given to memory location that can hold the data.
 The value of variable may change during the execution of PL/SQL block.
 Constant is variable to which a value is assigned it is not going to be changed
during the execution PL/SQL block.
 Since PL/SQL is procedural programming language, it provide support for
variables and constants like C, C++, Java, etc.
 Declaring Variable:
o Syntax:
NOTE: One should declare variable in DECLARE section of PL/SQL
block only.
 Defining Constant:
o Syntax:
NOTE: Here, ‘CONSTANT’ is keyword of PL/SQL. It is case insensitive.
For example:
name_of_variable datatype(size)
name_of_variable CONSTANT datatype(size):= value
DECLARE
x number(3); -- Variable declaration
pi constant number(4,3):= 3.142 --Constant Definition
BEGIN
x:= &x; -- Reading value for ‘x’ from keyboard
dbms_output.put_line(‘Entered number is=‘ || x);
dbms_output.put_line(‘Valye of pi=’ || pi);
END;
6 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
: Data Types in PL/SQL :
 The notation used in PL/SQL block to denote type of data is referred as data
type.
 PL/SQL provides a rich set of built-in data types.
 PL/SQL data types are classified into FOUR types as shown below:
Fig. PL/SQL Data types
PL/SQL Data
Scalar Data Composite Data
Reference LOB Data Types
7 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
1. Scalar Data Types:
 A data type that is used to define a variable that can store atomic (single)
value is referred as Scalar Data Type.
 For example,
INTEGER, it is used to declare a variable that can have only single
integer value.
 PL/SQL support total around 33 scalar data type as shown in above figure.
2. Composite Data Type:
 A data type which is use to define variable that can hold set of values re
referred as Composite Data Type.
 For example,
RECORD, this data type is used to declare a variable that can hold
all values in a single tuple of the table.
3. Reference Data Type:
 A data type used in PL/SQL block to represent a database object like,
table, cursor, trigger, etc. is referred as Reference Data Type.
4. LOB Data Type:
 LOB stands for ‘Large Object’.
 This kind of data type is used to refer large database object like, a file in
PL/SQL.
8 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
: Control Structures :
 Pl/SQL is procedural language.
 It provides control statements to handle Branching, Looping and Jumping.
 The control structures of PL/SQL are classified into following THREE types:
1. Conditional Control Structures:
 Simple IF:
o Syntax:
 For example, PL/SQL block to check largest number among three
given numbers using simple if.
IF codition THEN
TRUE block of statements
END IF;
DECLARE
a number(3); b number(3); c number(3);
BEGIN
a:= &a; b:= &b; c:= &c;
if a>b and a>c then
dbms_output.put_line(“ A is largest”);
end if;
if b>a and b>c then
dbms_output.put_line(“ B is largest”);
end if;
if c>a and c>b then
dbms_output.put_line(“ C is largest”);
end if;
END;
Control Structures
Conditional Looping Sequential
1. BREAK
2. CONTINUE
3. EXIT
4. GOTO
1. Simple LOOP
2. WHILE
3. FOR
1. Simple IF
2. IF-THEN-ELSE
3. ELSIF Ladder
4. CASE
9 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
 IF-THEN-ELSE:
o Syntax:
 For example, PL/SQL block to find given number is odd or even using
if-then-else statement:
Output:
Enter value for x: 45
ODD
IF codition THEN
True block of statement
ELSE
False block of statements
END IF;
DECLARE
x number(3);
BEGIN
x:= &x;
if mod(x,2)=0 then
dbms_output.put_line(“ EVEN”);
else
dbms_output.put_line(“ ODD”);
END;
10 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
 ELSIF Ladder:
o Syntax:
 For example, PL/SQL block to find grade obtained by student using
if-then-elsif----end if:
IF codition1 THEN
True block of statement-1
ELSIF condition2 THEN
True block of statement-2
.
.
.
.
ELSIF condition-N THEN
True block of statement-N
ELSE
Default block of statements
END IF;
DECLARE
per number(4,2);
BEGIN
per:= &per;
if per>=75 then
dbms_output.put_line(“Distinction”);
elsif per>=60 then
dbms_output.put_line(“Grade A”);
elsif per>=50 then
dbms_output.put_line(“Grade B”);
elsif per>=35 then
dbms_output.put_line(“Grade C”);
else
dbms_output.put_line(“FAIL”);
END;
11 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
 CASE statement:
o Syntax:
 For example, PL/SQL block to choose one color from the THREE
standard color:
CASE expt
WHEN value-1 THEN
True block of statement-1
WHEN value-2 THEN
True block of statement-2
.
.
.
.
WHEN value-N THEN
True block of statement-N
ELSE
Default block of statements
END CASE;
DECLARE
color char(1);
BEGIN
color:= &color;
case color
when ‘R’ then
dbms_output.put_line(“RED chosen”);
when ‘G’ then
dbms_output.put_line(“GREEN chosen”);
when ‘B’ then
dbms_output.put_line(“BLUE chosen”);
else
dbms_output.put_line(“Wrong choice…”);
end case;
END;
12 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
2. Looping Control Structures:
 In PL/SQL following three types of looping control structures are supported:
 Simple Loop
 While Loop
 For Loop
 Simple Loop:
o Syntax:
o For example: PL/SQL Block to print 1 to 10 numbers in ascending
order using simple LOOP
counter_valriable initialization;
LOOP
block of code
incr/decr of counter variable
EXIT WHEN condition;
END LOOP;
declare
i number(3);
begin
i := 1
loop
dbms_output.put_line(i)
i := i + 1
exit when i=11;
end loop;
end;
13 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
 WHILE Loop:
o Syntax:
o For example: PL/SQL Block to print 1 to 10 numbers in ascending
order using WHILE LOOP.
counter_valriable initialization;
WHILE condition LOOP
block of code
counter variable incr/decr
END LOOP;
declare
i number(3);
begin
i := 1
while i<=10 loop
dbms_output.put_line(i)
i := i + 1
end loop;
end;
14 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
 FOR Loop:
o Syntax:
 Here,
o START and END represent boundaries of range that expr can take.
o Only TWO dots(..) must be place between START and END
o The first value assigned to ‘expr’ is START and last value is END
o By default, START to END is incremented by 1.
o REVERSE is optional, if used then first value assigned to ‘expr’ will
be END and last value is START. That decrement by 1 takes place.
o For example: PL/SQL Block to print 1 to 10 numbers in descending
order using WHILE LOOP.
FOR expr IN [REVERSE] START..END LOOP
block of code
………………
END LOOP;
declare
i number(3);
begin
i := 1
for i in reverse 1..10 loop
dbms_output.put_line(i)
end loop;
end;
15 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
3. Sequential Control Structures:
 The following FOUR sequential control structures provided in PL/SQL for
jumping into a program from one point to another:
i. BREAK ii. CONTINUE
iii. EXIT iv. GOTO
DECLARE
i NUMBER(2);
j NUMBER := 0;
s NUMBER :=0;
BEGIN
x:=&x;
IF x<> 0 THEN GOTO xyz; END IF;
<<outer_loop>> -- LABEL
LOOP
i := i + 1;
<<inner_loop>> -- LABEL
LOOP
j := j + 1;
s := s + i * j;
CONTINUE inner_loop WHEN (i==3)
EXIT inner_loop WHEN (j > 5);
EXIT outer_loop WHEN ((i*j) > 15);
END LOOP inner_loop;
DBMS_OUTPUT.PUT_LINE('Sum:'|| s);
IF s > 100 THEN
EXIT;
END IF;
END LOOP outer_loop;
<< xyz >>
END;
16 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
:Cursor:
 Whenever an SQL statement is fired/executed, Oracle engine uses a work
area in main memory in order to store the resultant data of executed query.
This work area is private to the SQL statement fired and is called Cursor.
 NOTE:
i) Oracle has a pre-defined area in main memory set aside where cursors are
get opened.
ii) The data stored in the cursor is called the Active Data Set.
Ex. Consider the following table ‘EMP’:
EMPID ENAME SAL DOB DEPTNO
E101 ABC 4000 10-JUN-90 10
E102 MNO 8000 12-AUG-92 10
E103 PQR 10000 02-FEB-91 20
E104 XYZ 7000 04-MAR-90 30
SQL> select empid, ename, sal from emp
where deptno=10 OR deptno=30;
Fig. Active Data Set
17 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
: Types of Cursor :
 The cursors in Oracle are classified into following two basic types:
1. Implicit Cursors
2. Explicit Cursors
1. Implicit Cursor:
 The Oracle engine implicitly opens a cursor in server’s main memory for each
SQL statement that is fired to it.
 This cursor opened by the Oracle engine is called Implicit Cursor.
 The default name to this cursor is SQL.
2. Explicit Cursor:
 To process selected records from a table within a PL/SQL block, user can
define a cursor to hold those selected records, this user defined cursor is called
as Explicit Cursor.
 The name of the explicit cursor is defined by user.
 The following table shows few important attributes of cursor that user can
use:
Sr.
No.
Attribute Description
1 %FOUND
Returns TRUE if active data set found data. Otherwise
returns FALSE
2 %NOTFOUND It is opposite to %FOUND
3 %ISOPEN
It always returns FALSE for implicit cursors, because
Oracle closes this cursor automatically but explicit
cursor user has to close.
4 %ROWCOUNT Returns the number of rows in active data set.
Fig. Cursor Attributes
18 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
: Working with Explicit Cursor ;
 Working with an explicit cursor involves following four steps:
 Declaring a cursor
 Opening a cursor
 Fetching Cursor data
 Closing a cursor
 Declaring Cursor:
o The cursor is always declared in ‘DECLARE’ section of the PL/SQL
block.
o In cursor declaration, we have to select records in a table to be stored in
cursor using ‘SELECT’ statement.
o The syntax for Cursor declaration is:
 Opening Cursor:
o To open a cursor ‘OPEN’ command is provided in SQL.
o The ‘OPEN’ command performs the following tasks:
i) Allocate memory for the cursor and assign the name of the cursor to it.
ii) Populate/Fills the cursor with the records retrieved by ‘SELECT’
statement used in the declaration.
o The cursor always opened in ‘BEGIN’ section of PL/SQL block.
o Syntax:
DECLARE
CURSOR cursorname
IS
SQL ‘SELECT’ statement;
BEGIN
BEGIN
OPEN cursorname;
EXCEPTION
19 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
 Fetching records from Cursor:
o To move the data in the cursor i.e. Active Data Set into user defined
variable for the processing ‘FETCH’ command is used.
o Syntax:
 Closing Cursor:
o The CLOSE command is used to disable/close the cursor and the active
data set becomes undefined. It releases the memory occupied by the cursor.
o Syntax:
BEGIN
FETCH curname INTO variable1, variable2, …;
EXCEPTION
BEGIN
CLOSE cursorname;
EXCEPTION
DECLARE
id emp.empno%type; salary emp.sal%TYPE;
CURSOR X
IS
SELECT empno,sal FROM emp WHERE deptno=10;
BEGIN
OPEN X;
LOOP
FETCH X INTO id,salary;
EXIT WHEN X%NOTFOUND;
update emp set sal=salary+2000 where empno=id;
END LOOP;
CLOSE X;
END;
20 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
: Trigger and it’s Types :
Definition: (Trigger)
“A stored procedure (Block of Code) that is implicitly executed by
Oracle engine itself, when an insert, update or delete statement is issued against
the associated table is called as Trigger.”
Types of Trigger:
Depending upon the number of times the trigger to be executed, the
triggers are classified into TWO types:
1. Row Trigger: The trigger which is executed for each row affected by ‘WHEN’
condition, such a trigger is called Row Trigger. To create a
Row Trigger, we have to use FOR EACH ROW clause while
creating the trigger.
2. Statement Trigger: If ‘FOR EACH ROW’ clause is not specified, the trigger
created is a Statement Trigger. The statement triggers
should be created when triggering action is not depends
on number of rows affected.
Depending upon, when the trigger is to be executed, the triggers are
classified into following TWO types:
1. Before Trigger: The trigger which executed by Oracle Engine Before the
triggering event is called as Before Trigger. This type of
trigger is created by using ‘BEFORE’ clause while creating
the trigger.
2. After Trigger: The trigger which executed by Oracle Engine After the
triggering event is called as After Trigger. This type of trigger
is created by using ‘AFTER’ clause while creating the trigger.
21 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
: Creating Trigger :
 To create a trigger in Oracle, CREATE TRIGGER statement in provided in
SQL.
 Syntax:
Keywords and Parameters:
1.BEFORE: Indicates that the Oracle engine executes(fires) the trigger before
executing the triggering event.
2. AFTER: Indicates that the Oracle engine executes the (fires) the trigger after
executing the triggering event.
3. FOR EACH ROW: Indicates it is Row Trigger. If this clause is omitted the
trigger is a Statement Trigger.
SQL> CREATE TRIGGER triggername
{Before/After}
{Insert/Update/Delete}
ON tablename
[For each row]
[WHEN condition]
DECLARE
variable declerations;
BEGIN
SQL or PL/SQL statements;
END;
22 Prepared by, B.Sc. II (IV Sem)
Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)
For example,
 Consider the following two relations :
 STUDENT(rno, name)
 Stu_Entries(rno, entry_date, user_name)
 The following trigger ‘T1’ is executed implicitly by Oracle engine whenever
any ‘update’ or ‘delete’ statement is fired on table ‘STUDENT’.
 The trigger ‘T1’ inserts records into table ‘Stu_Entries’.
 The above created trigger is a AFTER trigger.
 We can create BEFORE trigger for same functionality just by replacing
‘AFTER’ keyword with ‘BEFORE’ in above example.
*************
SQL> CREATE TRIGGER T1
AFTER UPDATE OR DELETE
ON STUDENT
FOR EACH ROW
DECLARE
R STUDENT.RNO%TYPE;
BEGIN
R:=OLD.RNO;
INSERT INTO Stu_Entries
VALUES(R, SYSDATE, USER);
END;

More Related Content

What's hot (20)

PPTX
Difference between frontend and backend
Rahul Rana
 
PPTX
Selenium introduction
Pankaj Dubey
 
PPTX
SQLite - Overview
Emanuele Bartolesi
 
PPTX
Automation - web testing with selenium
Tzirla Rozental
 
PPT
Intro on Oracle Application express - APEX
Lino Schildenfeld
 
PDF
Real Life Clean Architecture
Mattia Battiston
 
PPTX
Sqlite
Raghu nath
 
PPT
Java database connectivity
Vaishali Modi
 
PPTX
Dependency injection presentation
Ahasanul Kalam Akib
 
PPTX
Vertical Slicing Architectures
Victor Rentea
 
PPTX
C# Interface | Interfaces In C# | C# Interfaces Explained | C# Tutorial For B...
Simplilearn
 
PPT
Design Pattern For C# Part 1
Shahzad
 
PPT
DOT Net overview
chandrasekhardesireddi
 
PPTX
Dotnet Basics Presentation
Sudhakar Sharma
 
PPTX
Best Practices for API Security
MuleSoft
 
PPTX
Microsoft DevOps Solution - DevOps
Chetan Gordhan
 
ODP
Selenium ppt
Anirudh Raja
 
PDF
Selenium Maven With Eclipse | Edureka
Edureka!
 
PPTX
Automation Testing by Selenium Web Driver
Cuelogic Technologies Pvt. Ltd.
 
PPTX
Flutter vs xamarin vs react native - Mobile App Development Framework
developeronrents
 
Difference between frontend and backend
Rahul Rana
 
Selenium introduction
Pankaj Dubey
 
SQLite - Overview
Emanuele Bartolesi
 
Automation - web testing with selenium
Tzirla Rozental
 
Intro on Oracle Application express - APEX
Lino Schildenfeld
 
Real Life Clean Architecture
Mattia Battiston
 
Sqlite
Raghu nath
 
Java database connectivity
Vaishali Modi
 
Dependency injection presentation
Ahasanul Kalam Akib
 
Vertical Slicing Architectures
Victor Rentea
 
C# Interface | Interfaces In C# | C# Interfaces Explained | C# Tutorial For B...
Simplilearn
 
Design Pattern For C# Part 1
Shahzad
 
DOT Net overview
chandrasekhardesireddi
 
Dotnet Basics Presentation
Sudhakar Sharma
 
Best Practices for API Security
MuleSoft
 
Microsoft DevOps Solution - DevOps
Chetan Gordhan
 
Selenium ppt
Anirudh Raja
 
Selenium Maven With Eclipse | Edureka
Edureka!
 
Automation Testing by Selenium Web Driver
Cuelogic Technologies Pvt. Ltd.
 
Flutter vs xamarin vs react native - Mobile App Development Framework
developeronrents
 

Similar to B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-5 PL/SQL, Cursor and Trigger (20)

PPTX
4. plsql
Amrit Kaur
 
PDF
PL/SQL Complete Tutorial. All Topics Covered
Danish Mehraj
 
PDF
Unit 4 rdbms study_material
gayaramesh
 
PPTX
PL SQL.pptx in computer language in database
ironman82715
 
PDF
rdbms.pdf plsql database system notes for students to study
rarelyused
 
PPT
Ppt on plssql study aboutnsmsmskskwkwkwkwk
DrStrange634619
 
PPTX
PL_SQL, Trigger, Cursor, Stored procedure ,function
RajendraKankrale1
 
PPT
L9 l10 server side programming
Rushdi Shams
 
PPTX
PL/SQL is a block structured language that enables developers to combine the ...
renuka b
 
PPTX
Ch as pbdasdadssadsadsadasdasdasdas fdt .pptx
sharmilasatishpore
 
PPTX
PLSQL Tutorial
Quang Minh Đoàn
 
PDF
RDBMS - UNIT 4.pdf,UNIT THREE AND UNIT FIVE
ajitharaja2003
 
PPT
10gplsqlslide-120704232925-phJKKJJKKJpapp01.ppt
Noorien3
 
PPTX
Pl sql Prograaming of Database management system
AjitPatil801582
 
PDF
Lecture Notes Unit5 chapter 15 PL/SQL Programming
Murugan146644
 
PPT
Chapter8 pl sql
Jafar Nesargi
 
PPTX
ORACLE PL/SQL
ASHABOOPATHY
 
PDF
Oracle PL/SQL online training | PL/SQL online Training
suresh
 
PPT
pl_sql.ppt
Prabhat106214
 
PDF
Dbms 2011
Atiqa Khan
 
4. plsql
Amrit Kaur
 
PL/SQL Complete Tutorial. All Topics Covered
Danish Mehraj
 
Unit 4 rdbms study_material
gayaramesh
 
PL SQL.pptx in computer language in database
ironman82715
 
rdbms.pdf plsql database system notes for students to study
rarelyused
 
Ppt on plssql study aboutnsmsmskskwkwkwkwk
DrStrange634619
 
PL_SQL, Trigger, Cursor, Stored procedure ,function
RajendraKankrale1
 
L9 l10 server side programming
Rushdi Shams
 
PL/SQL is a block structured language that enables developers to combine the ...
renuka b
 
Ch as pbdasdadssadsadsadasdasdasdas fdt .pptx
sharmilasatishpore
 
PLSQL Tutorial
Quang Minh Đoàn
 
RDBMS - UNIT 4.pdf,UNIT THREE AND UNIT FIVE
ajitharaja2003
 
10gplsqlslide-120704232925-phJKKJJKKJpapp01.ppt
Noorien3
 
Pl sql Prograaming of Database management system
AjitPatil801582
 
Lecture Notes Unit5 chapter 15 PL/SQL Programming
Murugan146644
 
Chapter8 pl sql
Jafar Nesargi
 
ORACLE PL/SQL
ASHABOOPATHY
 
Oracle PL/SQL online training | PL/SQL online Training
suresh
 
pl_sql.ppt
Prabhat106214
 
Dbms 2011
Atiqa Khan
 
Ad

More from Assistant Professor, Shri Shivaji Science College, Amravati (7)

PDF
B.Sc. III(VI Sem) Advance Java Unit3: AWT & Event Handling
Assistant Professor, Shri Shivaji Science College, Amravati
 
PDF
B.Sc. III(VI Sem) Advance Java Unit2: Appet
Assistant Professor, Shri Shivaji Science College, Amravati
 
PDF
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
Assistant Professor, Shri Shivaji Science College, Amravati
 
PDF
B.Sc. III(VI Sem) Question Bank Advance Java(Unit:1,2, and 5)
Assistant Professor, Shri Shivaji Science College, Amravati
 
PDF
B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-2 Relational Model
Assistant Professor, Shri Shivaji Science College, Amravati
 
PDF
B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-1 Fundamentals of DBMS
Assistant Professor, Shri Shivaji Science College, Amravati
 
B.Sc. III(VI Sem) Advance Java Unit3: AWT & Event Handling
Assistant Professor, Shri Shivaji Science College, Amravati
 
B.Sc. III(VI Sem) Advance Java Unit2: Appet
Assistant Professor, Shri Shivaji Science College, Amravati
 
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
Assistant Professor, Shri Shivaji Science College, Amravati
 
B.Sc. III(VI Sem) Question Bank Advance Java(Unit:1,2, and 5)
Assistant Professor, Shri Shivaji Science College, Amravati
 
B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-2 Relational Model
Assistant Professor, Shri Shivaji Science College, Amravati
 
B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-1 Fundamentals of DBMS
Assistant Professor, Shri Shivaji Science College, Amravati
 
Ad

Recently uploaded (20)

PDF
Treatment and safety of drinking water .
psuvethapalani
 
PDF
The ALMA-CRISTAL survey: Gas, dust, and stars in star-forming galaxies when t...
Sérgio Sacani
 
PDF
Adding Geochemistry To Understand Recharge Areas - Kinney County, Texas - Jim...
Texas Alliance of Groundwater Districts
 
PDF
High-speedBouldersandtheDebrisFieldinDARTEjecta
Sérgio Sacani
 
PDF
Unit-3 ppt.pdf organic chemistry unit 3 heterocyclic
visionshukla007
 
PPTX
Diagnostic Features of Common Oral Ulcerative Lesions.pptx
Dr Palak borade
 
PDF
Pharmakon of algorithmic alchemy: Marketing in the age of AI
Selcen Ozturkcan
 
PPTX
Phage Therapy and Bacteriophage Biology.pptx
Prachi Virat
 
PPTX
GB1 Q1 04 Life in a Cell (1).pptx GRADE 11
JADE ACOSTA
 
PPTX
PEDIA IDS IN A GIST_6488b6b5-3152-4a4a-a943-20a56efddd43 (2).pptx
tdas83504
 
PPTX
Bacillus thuringiensis.crops & golden rice
priyadharshini87125
 
PPTX
Ghent University Global Campus: Overview
Ghent University Global Campus
 
PPT
Restriction digestion of DNA for students of undergraduate and post graduate ...
DrMukeshRameshPimpli
 
PDF
Pharma Part 1.pdf #pharmacology #pharmacology
hikmatyt01
 
PDF
FYS 100 final presentation on Afro cubans
RowanSales
 
PPTX
CNS.pptx Central nervous system meninges ventricles of brain it's structure a...
Ashwini I Chuncha
 
PDF
Preserving brand authenticity amid AI-driven misinformation: Sustaining consu...
Selcen Ozturkcan
 
PPTX
770043401-q1-Ppt-pe-and-Health-7-week-1-lesson-1.pptx
AizaRazonado
 
PPTX
Akshay tunneling .pptx_20250331_165945_0000.pptx
akshaythaker18
 
PDF
A High-Caliber View of the Bullet Cluster through JWST Strong and Weak Lensin...
Sérgio Sacani
 
Treatment and safety of drinking water .
psuvethapalani
 
The ALMA-CRISTAL survey: Gas, dust, and stars in star-forming galaxies when t...
Sérgio Sacani
 
Adding Geochemistry To Understand Recharge Areas - Kinney County, Texas - Jim...
Texas Alliance of Groundwater Districts
 
High-speedBouldersandtheDebrisFieldinDARTEjecta
Sérgio Sacani
 
Unit-3 ppt.pdf organic chemistry unit 3 heterocyclic
visionshukla007
 
Diagnostic Features of Common Oral Ulcerative Lesions.pptx
Dr Palak borade
 
Pharmakon of algorithmic alchemy: Marketing in the age of AI
Selcen Ozturkcan
 
Phage Therapy and Bacteriophage Biology.pptx
Prachi Virat
 
GB1 Q1 04 Life in a Cell (1).pptx GRADE 11
JADE ACOSTA
 
PEDIA IDS IN A GIST_6488b6b5-3152-4a4a-a943-20a56efddd43 (2).pptx
tdas83504
 
Bacillus thuringiensis.crops & golden rice
priyadharshini87125
 
Ghent University Global Campus: Overview
Ghent University Global Campus
 
Restriction digestion of DNA for students of undergraduate and post graduate ...
DrMukeshRameshPimpli
 
Pharma Part 1.pdf #pharmacology #pharmacology
hikmatyt01
 
FYS 100 final presentation on Afro cubans
RowanSales
 
CNS.pptx Central nervous system meninges ventricles of brain it's structure a...
Ashwini I Chuncha
 
Preserving brand authenticity amid AI-driven misinformation: Sustaining consu...
Selcen Ozturkcan
 
770043401-q1-Ppt-pe-and-Health-7-week-1-lesson-1.pptx
AizaRazonado
 
Akshay tunneling .pptx_20250331_165945_0000.pptx
akshaythaker18
 
A High-Caliber View of the Bullet Cluster through JWST Strong and Weak Lensin...
Sérgio Sacani
 

B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-5 PL/SQL, Cursor and Trigger

  • 1. 1 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V) UNIT-V: PL/SQL, Cursor and Trigger Introduction to PL/SQL:  SQL is the natural language of Oracle.  Although SQL is very powerful tool, it suffers from following some major disadvantages.  The disadvantages of SQL are: o SQL does not have programming techniques such as looping and branching. o SQL statements are passed to Oracle Engine one at a time. o SQL does not have facility to define programmer defined error messages. Because of these disadvantages we cannot use SQL as conventional programming language. Hence, Oracle provides a fully structured language called, PL/SQL.  The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as procedural extension language for SQL.  Advantages of PL/SQL: o Tight Integration with SQL:  PL/SQL lets you use all SQL data manipulation, cursor control, and transaction control statements, and all SQL functions, operators.  PL/SQL fully supports SQL data types. o High Performance:  PL/SQL lets you to send block of statements as a unit to Oracle engine rather sending single statement like SQL. 2 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V) o High Productivity:  PL/SQL lets you write compact code for manipulating data just as a scripting language like PERL that can read, transform, and write data in files. o Portability:  You can run PL/SQL applications on any operating system and platform where Oracle Database runs. o Support for Programming Techniques:  We can implement decision making and looping techniques in PL/SQL block like in other standard programming languages. o Reusability:  PL/SQL allow to create stored subprograms and let them use any number of applications without maintaining duplicate copies of subprograms. o Support for Object Oriented Programming:  PL/SQL supports object-oriented programming with "Abstract Data Types". o Support for developing Web application:  PL/SQL lets you create applications that generate web pages directly from the database, allowing you to make your database available on the Web and make back-office data accessible on the intranet.
  • 2. 3 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V) PL/SQL Block Structure: Fig. Generic structure of PL/SQL Block  A generic PL/SQL block is consisting following FOUR sections: 1. DECLARE section 2. BEGIN section 3. EXCEPTION section 4. END section 1. Declare Section: It contains declaration of memory variables used later in BEGIN section. 2. Begin Section: It contains SQL executable statements for manipulating table data as well as procedural statements. The executable statements should be present in BEGIN....END block. 3. Exception Section: It is optional section. It contains code for handling errors that generate in above PL/SQL block. 4. END Section: It indicates end of PL/SQL block. It should be terminated with semicolon. DECLARE BEGIN [EXCEPTION] END; Declarations of variables, constants cursors, etc. SQL executable statements PL/SQL executable statements SQL or PL/SQL code to handle user defined errors during the execution of PL/SQL block 4 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V) For example, Output: Enter value for x : 10 Entered number is= 10 DECLARE x number(3); -- Variable declaration BEGIN x:= &x; -- Reading value for ‘x’ from keyboard dbms_output.put_line(‘Entered number is=‘ || x); END;
  • 3. 5 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V) :Variable and Constants:  Variable is nothing but name given to memory location that can hold the data.  The value of variable may change during the execution of PL/SQL block.  Constant is variable to which a value is assigned it is not going to be changed during the execution PL/SQL block.  Since PL/SQL is procedural programming language, it provide support for variables and constants like C, C++, Java, etc.  Declaring Variable: o Syntax: NOTE: One should declare variable in DECLARE section of PL/SQL block only.  Defining Constant: o Syntax: NOTE: Here, ‘CONSTANT’ is keyword of PL/SQL. It is case insensitive. For example: name_of_variable datatype(size) name_of_variable CONSTANT datatype(size):= value DECLARE x number(3); -- Variable declaration pi constant number(4,3):= 3.142 --Constant Definition BEGIN x:= &x; -- Reading value for ‘x’ from keyboard dbms_output.put_line(‘Entered number is=‘ || x); dbms_output.put_line(‘Valye of pi=’ || pi); END; 6 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V) : Data Types in PL/SQL :  The notation used in PL/SQL block to denote type of data is referred as data type.  PL/SQL provides a rich set of built-in data types.  PL/SQL data types are classified into FOUR types as shown below: Fig. PL/SQL Data types PL/SQL Data Scalar Data Composite Data Reference LOB Data Types
  • 4. 7 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V) 1. Scalar Data Types:  A data type that is used to define a variable that can store atomic (single) value is referred as Scalar Data Type.  For example, INTEGER, it is used to declare a variable that can have only single integer value.  PL/SQL support total around 33 scalar data type as shown in above figure. 2. Composite Data Type:  A data type which is use to define variable that can hold set of values re referred as Composite Data Type.  For example, RECORD, this data type is used to declare a variable that can hold all values in a single tuple of the table. 3. Reference Data Type:  A data type used in PL/SQL block to represent a database object like, table, cursor, trigger, etc. is referred as Reference Data Type. 4. LOB Data Type:  LOB stands for ‘Large Object’.  This kind of data type is used to refer large database object like, a file in PL/SQL. 8 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V) : Control Structures :  Pl/SQL is procedural language.  It provides control statements to handle Branching, Looping and Jumping.  The control structures of PL/SQL are classified into following THREE types: 1. Conditional Control Structures:  Simple IF: o Syntax:  For example, PL/SQL block to check largest number among three given numbers using simple if. IF codition THEN TRUE block of statements END IF; DECLARE a number(3); b number(3); c number(3); BEGIN a:= &a; b:= &b; c:= &c; if a>b and a>c then dbms_output.put_line(“ A is largest”); end if; if b>a and b>c then dbms_output.put_line(“ B is largest”); end if; if c>a and c>b then dbms_output.put_line(“ C is largest”); end if; END; Control Structures Conditional Looping Sequential 1. BREAK 2. CONTINUE 3. EXIT 4. GOTO 1. Simple LOOP 2. WHILE 3. FOR 1. Simple IF 2. IF-THEN-ELSE 3. ELSIF Ladder 4. CASE
  • 5. 9 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)  IF-THEN-ELSE: o Syntax:  For example, PL/SQL block to find given number is odd or even using if-then-else statement: Output: Enter value for x: 45 ODD IF codition THEN True block of statement ELSE False block of statements END IF; DECLARE x number(3); BEGIN x:= &x; if mod(x,2)=0 then dbms_output.put_line(“ EVEN”); else dbms_output.put_line(“ ODD”); END; 10 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)  ELSIF Ladder: o Syntax:  For example, PL/SQL block to find grade obtained by student using if-then-elsif----end if: IF codition1 THEN True block of statement-1 ELSIF condition2 THEN True block of statement-2 . . . . ELSIF condition-N THEN True block of statement-N ELSE Default block of statements END IF; DECLARE per number(4,2); BEGIN per:= &per; if per>=75 then dbms_output.put_line(“Distinction”); elsif per>=60 then dbms_output.put_line(“Grade A”); elsif per>=50 then dbms_output.put_line(“Grade B”); elsif per>=35 then dbms_output.put_line(“Grade C”); else dbms_output.put_line(“FAIL”); END;
  • 6. 11 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)  CASE statement: o Syntax:  For example, PL/SQL block to choose one color from the THREE standard color: CASE expt WHEN value-1 THEN True block of statement-1 WHEN value-2 THEN True block of statement-2 . . . . WHEN value-N THEN True block of statement-N ELSE Default block of statements END CASE; DECLARE color char(1); BEGIN color:= &color; case color when ‘R’ then dbms_output.put_line(“RED chosen”); when ‘G’ then dbms_output.put_line(“GREEN chosen”); when ‘B’ then dbms_output.put_line(“BLUE chosen”); else dbms_output.put_line(“Wrong choice…”); end case; END; 12 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V) 2. Looping Control Structures:  In PL/SQL following three types of looping control structures are supported:  Simple Loop  While Loop  For Loop  Simple Loop: o Syntax: o For example: PL/SQL Block to print 1 to 10 numbers in ascending order using simple LOOP counter_valriable initialization; LOOP block of code incr/decr of counter variable EXIT WHEN condition; END LOOP; declare i number(3); begin i := 1 loop dbms_output.put_line(i) i := i + 1 exit when i=11; end loop; end;
  • 7. 13 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)  WHILE Loop: o Syntax: o For example: PL/SQL Block to print 1 to 10 numbers in ascending order using WHILE LOOP. counter_valriable initialization; WHILE condition LOOP block of code counter variable incr/decr END LOOP; declare i number(3); begin i := 1 while i<=10 loop dbms_output.put_line(i) i := i + 1 end loop; end; 14 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)  FOR Loop: o Syntax:  Here, o START and END represent boundaries of range that expr can take. o Only TWO dots(..) must be place between START and END o The first value assigned to ‘expr’ is START and last value is END o By default, START to END is incremented by 1. o REVERSE is optional, if used then first value assigned to ‘expr’ will be END and last value is START. That decrement by 1 takes place. o For example: PL/SQL Block to print 1 to 10 numbers in descending order using WHILE LOOP. FOR expr IN [REVERSE] START..END LOOP block of code ……………… END LOOP; declare i number(3); begin i := 1 for i in reverse 1..10 loop dbms_output.put_line(i) end loop; end;
  • 8. 15 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V) 3. Sequential Control Structures:  The following FOUR sequential control structures provided in PL/SQL for jumping into a program from one point to another: i. BREAK ii. CONTINUE iii. EXIT iv. GOTO DECLARE i NUMBER(2); j NUMBER := 0; s NUMBER :=0; BEGIN x:=&x; IF x<> 0 THEN GOTO xyz; END IF; <<outer_loop>> -- LABEL LOOP i := i + 1; <<inner_loop>> -- LABEL LOOP j := j + 1; s := s + i * j; CONTINUE inner_loop WHEN (i==3) EXIT inner_loop WHEN (j > 5); EXIT outer_loop WHEN ((i*j) > 15); END LOOP inner_loop; DBMS_OUTPUT.PUT_LINE('Sum:'|| s); IF s > 100 THEN EXIT; END IF; END LOOP outer_loop; << xyz >> END; 16 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V) :Cursor:  Whenever an SQL statement is fired/executed, Oracle engine uses a work area in main memory in order to store the resultant data of executed query. This work area is private to the SQL statement fired and is called Cursor.  NOTE: i) Oracle has a pre-defined area in main memory set aside where cursors are get opened. ii) The data stored in the cursor is called the Active Data Set. Ex. Consider the following table ‘EMP’: EMPID ENAME SAL DOB DEPTNO E101 ABC 4000 10-JUN-90 10 E102 MNO 8000 12-AUG-92 10 E103 PQR 10000 02-FEB-91 20 E104 XYZ 7000 04-MAR-90 30 SQL> select empid, ename, sal from emp where deptno=10 OR deptno=30; Fig. Active Data Set
  • 9. 17 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V) : Types of Cursor :  The cursors in Oracle are classified into following two basic types: 1. Implicit Cursors 2. Explicit Cursors 1. Implicit Cursor:  The Oracle engine implicitly opens a cursor in server’s main memory for each SQL statement that is fired to it.  This cursor opened by the Oracle engine is called Implicit Cursor.  The default name to this cursor is SQL. 2. Explicit Cursor:  To process selected records from a table within a PL/SQL block, user can define a cursor to hold those selected records, this user defined cursor is called as Explicit Cursor.  The name of the explicit cursor is defined by user.  The following table shows few important attributes of cursor that user can use: Sr. No. Attribute Description 1 %FOUND Returns TRUE if active data set found data. Otherwise returns FALSE 2 %NOTFOUND It is opposite to %FOUND 3 %ISOPEN It always returns FALSE for implicit cursors, because Oracle closes this cursor automatically but explicit cursor user has to close. 4 %ROWCOUNT Returns the number of rows in active data set. Fig. Cursor Attributes 18 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V) : Working with Explicit Cursor ;  Working with an explicit cursor involves following four steps:  Declaring a cursor  Opening a cursor  Fetching Cursor data  Closing a cursor  Declaring Cursor: o The cursor is always declared in ‘DECLARE’ section of the PL/SQL block. o In cursor declaration, we have to select records in a table to be stored in cursor using ‘SELECT’ statement. o The syntax for Cursor declaration is:  Opening Cursor: o To open a cursor ‘OPEN’ command is provided in SQL. o The ‘OPEN’ command performs the following tasks: i) Allocate memory for the cursor and assign the name of the cursor to it. ii) Populate/Fills the cursor with the records retrieved by ‘SELECT’ statement used in the declaration. o The cursor always opened in ‘BEGIN’ section of PL/SQL block. o Syntax: DECLARE CURSOR cursorname IS SQL ‘SELECT’ statement; BEGIN BEGIN OPEN cursorname; EXCEPTION
  • 10. 19 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V)  Fetching records from Cursor: o To move the data in the cursor i.e. Active Data Set into user defined variable for the processing ‘FETCH’ command is used. o Syntax:  Closing Cursor: o The CLOSE command is used to disable/close the cursor and the active data set becomes undefined. It releases the memory occupied by the cursor. o Syntax: BEGIN FETCH curname INTO variable1, variable2, …; EXCEPTION BEGIN CLOSE cursorname; EXCEPTION DECLARE id emp.empno%type; salary emp.sal%TYPE; CURSOR X IS SELECT empno,sal FROM emp WHERE deptno=10; BEGIN OPEN X; LOOP FETCH X INTO id,salary; EXIT WHEN X%NOTFOUND; update emp set sal=salary+2000 where empno=id; END LOOP; CLOSE X; END; 20 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V) : Trigger and it’s Types : Definition: (Trigger) “A stored procedure (Block of Code) that is implicitly executed by Oracle engine itself, when an insert, update or delete statement is issued against the associated table is called as Trigger.” Types of Trigger: Depending upon the number of times the trigger to be executed, the triggers are classified into TWO types: 1. Row Trigger: The trigger which is executed for each row affected by ‘WHEN’ condition, such a trigger is called Row Trigger. To create a Row Trigger, we have to use FOR EACH ROW clause while creating the trigger. 2. Statement Trigger: If ‘FOR EACH ROW’ clause is not specified, the trigger created is a Statement Trigger. The statement triggers should be created when triggering action is not depends on number of rows affected. Depending upon, when the trigger is to be executed, the triggers are classified into following TWO types: 1. Before Trigger: The trigger which executed by Oracle Engine Before the triggering event is called as Before Trigger. This type of trigger is created by using ‘BEFORE’ clause while creating the trigger. 2. After Trigger: The trigger which executed by Oracle Engine After the triggering event is called as After Trigger. This type of trigger is created by using ‘AFTER’ clause while creating the trigger.
  • 11. 21 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V) : Creating Trigger :  To create a trigger in Oracle, CREATE TRIGGER statement in provided in SQL.  Syntax: Keywords and Parameters: 1.BEFORE: Indicates that the Oracle engine executes(fires) the trigger before executing the triggering event. 2. AFTER: Indicates that the Oracle engine executes the (fires) the trigger after executing the triggering event. 3. FOR EACH ROW: Indicates it is Row Trigger. If this clause is omitted the trigger is a Statement Trigger. SQL> CREATE TRIGGER triggername {Before/After} {Insert/Update/Delete} ON tablename [For each row] [WHEN condition] DECLARE variable declerations; BEGIN SQL or PL/SQL statements; END; 22 Prepared by, B.Sc. II (IV Sem) Mr. Hushare Y.V. [M.Sc., MCA, SET], Asst. Professor RDBMS and PL/SQL (Unit-V) For example,  Consider the following two relations :  STUDENT(rno, name)  Stu_Entries(rno, entry_date, user_name)  The following trigger ‘T1’ is executed implicitly by Oracle engine whenever any ‘update’ or ‘delete’ statement is fired on table ‘STUDENT’.  The trigger ‘T1’ inserts records into table ‘Stu_Entries’.  The above created trigger is a AFTER trigger.  We can create BEFORE trigger for same functionality just by replacing ‘AFTER’ keyword with ‘BEFORE’ in above example. ************* SQL> CREATE TRIGGER T1 AFTER UPDATE OR DELETE ON STUDENT FOR EACH ROW DECLARE R STUDENT.RNO%TYPE; BEGIN R:=OLD.RNO; INSERT INTO Stu_Entries VALUES(R, SYSDATE, USER); END;