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

PDF
Operator overloading C++
PPTX
Data members and member functions
PPTX
Access specifier
PPTX
07. Virtual Functions
PPTX
Constructor in java
PPTX
Static Data Members and Member Functions
PPT
Operators in C++
PPTX
Inheritance in c++
Operator overloading C++
Data members and member functions
Access specifier
07. Virtual Functions
Constructor in java
Static Data Members and Member Functions
Operators in C++
Inheritance in c++

What's hot (20)

PPTX
Inheritance in c++
PPTX
Virtual base class
PPT
friend function(c++)
PPTX
Function overloading and overriding
PPTX
Inline function
PPTX
Friend functions
PPTX
Classes and objects in c++
PPT
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
PPTX
Polymorphism In c++
PPTX
1 unit (oops)
PPTX
Type casting in java
PPTX
Type casting in c programming
PPTX
Inheritance in java
PPTX
Data types
PPT
Inheritance : Extending Classes
PPT
07 Using Oracle-Supported Package in Application Development
PPTX
INLINE FUNCTION IN C++
PPTX
Friend function
PPTX
Oops concept in c++ unit 3 -topic 4
PPTX
[OOP - Lec 19] Static Member Functions
Inheritance in c++
Virtual base class
friend function(c++)
Function overloading and overriding
Inline function
Friend functions
Classes and objects in c++
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
Polymorphism In c++
1 unit (oops)
Type casting in java
Type casting in c programming
Inheritance in java
Data types
Inheritance : Extending Classes
07 Using Oracle-Supported Package in Application Development
INLINE FUNCTION IN C++
Friend function
Oops concept in c++ unit 3 -topic 4
[OOP - Lec 19] Static Member Functions
Ad

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

PDF
Dbms 2011
PDF
DBMS 2011
PDF
Procedural Language/Structured Query Language
PDF
Pl sql-ch1
PDF
PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdf
PDF
PL/SQL Complete Tutorial. All Topics Covered
PDF
rdbms.pdf plsql database system notes for students to study
PPT
Chapter8 pl sql
PDF
Oracle Introduction
PDF
Dbmsunit v
PDF
Unit 4 rdbms study_material
PPTX
PL_SQL, Trigger, Cursor, Stored procedure ,function
PPTX
PL/SQL is a block structured language that enables developers to combine the ...
PPTX
Pl sql chapter 1
PPTX
Ch as pbdasdadssadsadsadasdasdasdas fdt .pptx
PDF
Sql tutorial
PPTX
PL SQL.pptx in computer language in database
PDF
Advanced SQL - Database Access from Programming Languages
PDF
chapter 1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbb
PPTX
Cursors, triggers, procedures
Dbms 2011
DBMS 2011
Procedural Language/Structured Query Language
Pl sql-ch1
PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdf
PL/SQL Complete Tutorial. All Topics Covered
rdbms.pdf plsql database system notes for students to study
Chapter8 pl sql
Oracle Introduction
Dbmsunit v
Unit 4 rdbms study_material
PL_SQL, Trigger, Cursor, Stored procedure ,function
PL/SQL is a block structured language that enables developers to combine the ...
Pl sql chapter 1
Ch as pbdasdadssadsadsadasdasdasdas fdt .pptx
Sql tutorial
PL SQL.pptx in computer language in database
Advanced SQL - Database Access from Programming Languages
chapter 1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbb
Cursors, triggers, procedures
Ad

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

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

Recently uploaded (20)

PPT
protein biochemistry.ppt for university classes
PPTX
Classification Systems_TAXONOMY_SCIENCE8.pptx
PPTX
INTRODUCTION TO EVS | Concept of sustainability
PPTX
Cell Membrane: Structure, Composition & Functions
PPTX
Comparative Structure of Integument in Vertebrates.pptx
PDF
IFIT3 RNA-binding activity primores influenza A viruz infection and translati...
PPTX
Microbiology with diagram medical studies .pptx
PPTX
Vitamins & Minerals: Complete Guide to Functions, Food Sources, Deficiency Si...
PPTX
famous lake in india and its disturibution and importance
PDF
Sciences of Europe No 170 (2025)
PPTX
The KM-GBF monitoring framework – status & key messages.pptx
PDF
Unveiling a 36 billion solar mass black hole at the centre of the Cosmic Hors...
PPTX
G5Q1W8 PPT SCIENCE.pptx 2025-2026 GRADE 5
PPTX
SCIENCE10 Q1 5 WK8 Evidence Supporting Plate Movement.pptx
PPTX
TOTAL hIP ARTHROPLASTY Presentation.pptx
PPTX
Derivatives of integument scales, beaks, horns,.pptx
PDF
Biophysics 2.pdffffffffffffffffffffffffff
PDF
Mastering Bioreactors and Media Sterilization: A Complete Guide to Sterile Fe...
PPTX
7. General Toxicologyfor clinical phrmacy.pptx
PDF
Formation of Supersonic Turbulence in the Primordial Star-forming Cloud
protein biochemistry.ppt for university classes
Classification Systems_TAXONOMY_SCIENCE8.pptx
INTRODUCTION TO EVS | Concept of sustainability
Cell Membrane: Structure, Composition & Functions
Comparative Structure of Integument in Vertebrates.pptx
IFIT3 RNA-binding activity primores influenza A viruz infection and translati...
Microbiology with diagram medical studies .pptx
Vitamins & Minerals: Complete Guide to Functions, Food Sources, Deficiency Si...
famous lake in india and its disturibution and importance
Sciences of Europe No 170 (2025)
The KM-GBF monitoring framework – status & key messages.pptx
Unveiling a 36 billion solar mass black hole at the centre of the Cosmic Hors...
G5Q1W8 PPT SCIENCE.pptx 2025-2026 GRADE 5
SCIENCE10 Q1 5 WK8 Evidence Supporting Plate Movement.pptx
TOTAL hIP ARTHROPLASTY Presentation.pptx
Derivatives of integument scales, beaks, horns,.pptx
Biophysics 2.pdffffffffffffffffffffffffff
Mastering Bioreactors and Media Sterilization: A Complete Guide to Sterile Fe...
7. General Toxicologyfor clinical phrmacy.pptx
Formation of Supersonic Turbulence in the Primordial Star-forming Cloud

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;