0% found this document useful (0 votes)
17 views23 pages

RDBMS Unit-4

PL/SQL, or Procedural Language/Structured Query Language, serves as a powerful extension of SQL for database programming. Its introduction typically encompasses an overview of its purpose and capabilities within the database environment. One approach to database programming involves leveraging PL/SQL through various methods, including function calls, Embedded SQL utilizing CURSORs, Dynamic SQL for flexible querying, and integrating SQL commands within Java applications, alongside techniques lik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views23 pages

RDBMS Unit-4

PL/SQL, or Procedural Language/Structured Query Language, serves as a powerful extension of SQL for database programming. Its introduction typically encompasses an overview of its purpose and capabilities within the database environment. One approach to database programming involves leveraging PL/SQL through various methods, including function calls, Embedded SQL utilizing CURSORs, Dynamic SQL for flexible querying, and integrating SQL commands within Java applications, alongside techniques lik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….

Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

PL/SQL
● Introduction to PL/SQL
● Approaches to database programming: with function calls, Embedded SQL using
CURSORs, Dynamic SQL, SQL commands in Java, Retrieving multiple triples using
Iterators
● Advantages of PL/SQL
● Features of PL/SQL :Blocks structure, Error handling, Input and output designing,
variables and constant, data abstraction, control structures and subprogram
● Fundamentals of PL/SQL : character sets, lexical, delimeters, identifiers, declarations,
scope and visibility, Static and dynamic and static SQL, Implicit and explicit locking

UNIT-4

# Introduction to PL/SQL
PL/SQL is a combination of SQL along with the procedural features of programming
languages. It was developed by Oracle Corporation in the early 90's to enhance the
capabilities of SQL. In other words, it is a database-oriented programming language that is
a powerful extension of SQL with procedural capabilities. The key strength of PL/SQL is its
tight integration with the Oracle database.
Being a procedural language, it has many standard capabilities including
 Variable Definition and Assignment
 Conditional Processing
 Loop Constructs
 Error Handling
 Seamless Integration of SQL and SQL Functions

#Advantages of PL/SQL
PL/SQL offers several advantages over other programming languages. PL/SQL has these
advantages:
PL/SQL has these advantages:
1. Block Structure: PL SQL consists of blocks of code, which can be nested within
each other. Each block forms a unit of a task or a logical module. PL/SQL Blocks
can be stored in the database and reused.
2. Tight Integration with SQL: PL/SQL is tightly integrated with SQL, the most widely
used database manipulation language. For example: PL/SQL lets you use all SQL
data manipulation, cursor control, and transaction control statements, and all SQL
functions, operators, and pseudo-columns. It also fully supports SQL data types.
3. Procedural Language Capability: PL SQL consists of procedural language
constructs such as conditional statements (if else statements) and loops like (FOR
loops).

1
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103
4. High Performance: In PL/SQL, you send a block of statements to the database,
significantly reducing traffic between the application and the database.
5. High Productivity: In PL/SQL, you write compact code for manipulating data. Just
as a scripting language like PERL can read, transform, and write data in files,
PL/SQL can query, transform, and update data in a database.
6. Portability: You can run PL/SQL applications on any operating system and platform
where Oracle Database runs.
7. Scalability: PL/SQL stored subprograms increase scalability by centralizing
application processing on the database server. The shared memory facilities of the
shared server let Oracle Database support thousands of concurrent users on a single
node.
8. Manageability: PL/SQL stored subprograms increase manageability because you
can maintain only one copy of a subprogram, on the database server, rather than
one copy on each client system. Any number of applications can use the
subprograms, and you can change the subprograms without affecting the
applications that invoke them.
9. Support for Object-Oriented Programming: PL/SQL supports object-oriented
programming with "Abstract Data Types".
10. Support for Developing Web Applications: PL/SQL support to 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.
11. Support for Developing Server Pages: PL/SQL Server Pages (PSPs) let you develop
web pages with dynamic content. PSPs are an alternative to coding a stored
subprogram that writes the HTML code for a web page one line at a time.
12. Error Handling: PL/SQL handles errors or exceptions effectively during the
execution of a PL/SQL program. Once an exception is caught, specific actions can be
taken depending upon the type of the exception or it can be displayed to the user
with a message.

# Disadvantages of PL SQL
The disadvantages of PL/SQL are mentioned below:
 Limited I/O features – PL/SQL provides very limited support for I/O either to
read/write files or to read from or write to a user interface.
 Complex syntax – Sometimes, PL/SQL is not very easy for programmers to follow
due to its complex and inconsistent syntax.
 Proprietary to Oracle – It means that if one has to change the database vendors
then the user would have to update all the existing Oracle PL/SQL code. It is a bit
expensive.
 Not beginner-friendly – Certain concepts in PL/SQL can become difficult for
beginners to understand.

2
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

#Features of PL/SQL
Main Features of PL/SQL PL/SQL combines the data-manipulating power of SQL with the
processing power of procedural languages.
1. Error Handling
PL/SQL handles errors or exceptions effectively during the execution of a PL/SQL
program. Once an exception is caught, specific actions can be taken depending upon
the type of the exception or it can be displayed to the user with a message.
2. Blocks Structure
PL SQL consists of blocks of code, which can be nested within each other. Each
block forms a unit of a task or a logical module. PL/SQL Blocks can be stored in the
database and reused.

3. Variables and Constants


It give you control to declare variable and access them within the block. It also
support constant values which when declared remain fixed throughout the PL/SQL
block.
4. Subprograms
A PL/SQL subprogram is a named PL/SQL block that can be invoked repeatedly. If
the subprogram has parameters; their values can differ for each invocation. PL/SQL
has two types of subprograms, procedures and functions.
5. Packages
A package is a schema object that groups logically related PL/SQL types, variables,
constants, subprograms, cursors, and exceptions. A package is compiled and stored
in the database, where many applications can share its contents. You can think of a
package as an application.
6. Triggers
A trigger is a named PL/SQL unit that is stored in the database and run in response
to an event that occurs in the database. You can specify the event, whether the
trigger fires before or after the event, and whether the trigger runs for each event or
for each row affected by the event. For example, you can create a trigger that runs
every time an INSERT statement affects the EMPLOYEES table.
7. Input and Output
Most PL/SQL input and output (I/O) is done with SQL statements that store data in
database tables or query those tables.
8. Data Abstraction
Data abstraction lets you work with the essential properties of data without being too
involved with details. Some essential properties are- Cursors, Composite Variables,
Using the %ROWTYPE Attribute, Using the %TYPE Attribute, Abstract Data Types
9. Control Statements
Control statements are the most important PL/SQL extension to SQL. PL/SQL has
three categories of control statements: Conditional selection statements, Loop
statements, Sequential control statements.

3
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

10. Conditional Compilation


Conditional compilation lets you customize the functionality in a PL/SQL application
without removing source text.For example, you can:
 Use new features with the latest database release, and disable them when
running the application in an older database release.
 Activate debugging or tracing statements in the development environment,
and hide them when running the application at a production site.
11. Processing a Query Result Set One Row at a Time
PL/SQL lets you issue a SQL query and process the rows of the result set one at a
time. You can use a basic loop, or you can control the process precisely by using
individual statements to run the query, retrieve the results, and finish processing.

4
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

#Comparisons of SQL and PLSQL:


Sr. Basis of
SQL PL/SQL
No. Comparison

It is a database Structured It is a database programming


1. Definition
Query Language. language using SQL.

Variables, constraints, and data


Variables are not available in
2. Variables types features are available in
SQL.
PL/SQL.

No Supported Control Control Structures are available


Control
3. Structures like for loop, if, and like, for loop, while loop, if, and
structures
other. other.

Nature of It is an application-oriented
4. It is a Data-oriented language.
Orientation language.

PL/SQL block performs Group of


Query performs the single Operation as a single block
5. Operations
operation in SQL. resulting in reduced network
traffic.

Declarative/
PL/SQL is a procedural
6. Procedural SQL is a declarative language.
language.
Language

SQL can be embedded in PL/SQL can’t be embedded in


7. Embed
PL/SQL. SQL.

Interaction It directly interacts with the It does not interact directly with
8.
with Server database server. the database server.

Exception SQL does not provide error and PL/SQL provides error and
9.
Handling exception handling. exception handling.

It is used to write queries using The code blocks, functions,


10. Writes DDL (Data Definition procedures triggers, and
Language) and DML (Data packages can be written using

5
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

Sr. Basis of
SQL PL/SQL
No. Comparison

Manipulation Language) PL/SQL.


statements.

Processing SQL does not offer a high PL/SQL offers a high processing
11. Speed processing speed for speed for voluminous data.
voluminous data.

Application You can fetch, alter, add, You can use PL/SQL to develop
delete, or manipulate data in a applications that show
12.
database using SQL. information from SQL in a
logical manner.

6
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

# PL/SQL Block Structure

HEADER -- Header part (optional)


<< label >> (optional)
DECLARE -- Declarative part (optional)
-- Declarations of local types, variables, & subprograms
BEGIN -- Executable part (required)
-- Statements (which can use items declared in declarative part)
[EXCEPTION -- Exception-handling part (optional)
-- Exception handlers for exceptions (errors) raised in executable part]
END;

A PL/SQL Block consists of the following sections:


 The Header section (optional).
 The Declaration section (optional).
 The Execution section (mandatory).

The Exception (Error Handling) section (optional)


 Header Section:
The Header section of a PL/SQL Block is relevant only for subprograms. The Header
determines the way that the subprogram must be called. The header includes the name,
parameter list and RETURN clause (for a function only).
 Declaration Section:
The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE. This
section is optional and is used to declare any placeholders like variables, constants, records
and cursors, which are used to manipulate data in the execution section. Placeholders may
be any of Variables, Constants and Records, which stores data temporarily. Cursors are also
declared in this section.
 Execution Section:
The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends
with END. This is a mandatory section and is the section where the program logic is written
to perform any task. The programmatic constructs like loops, conditional statement and SQL
statements form a part of execution section.
 Exception Section:
The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. This
section is optional. Any errors in the program can be handled in this section, so that the
PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains exceptions that cannot be
handled, the Block terminates abruptly with errors. Every statement in the above three
sections must end with a semicolon (;). PL/SQL blocks can be nested within other PL/SQL
blocks. Comments can be used to document code.

7
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

# Fundamentals of PL/SQL
The PL/SQL language fundamental components are explained.
1. Character Sets
2. Lexical Units
3. Scope and Visibility of Identifiers
4. Expressions

1. Character Sets
Any character data to be processed by PL/SQL or stored in a database must be represented
as a sequence of bytes. The byte representation of a single character is called a character
code. A set of character codes is called a character set.
Every database character set includes these basic characters:
• Latin letters: A through Z and a through z
• Decimal digits: 0 through 9
• Punctuation characters: ( ) < > + - * / = ‘ “ : ; . %
• Whitespace characters: space, tab, new line,

2. Lexical Units
The lexical units of PL/SQL are its smallest individual components —
o Delimiters: A delimiter is a character, or character combination, that has a special
meaning in PL/SQL.
o Identifiers: Identifiers name PL/SQL elements, which include: Constants, Cursors,
Exceptions, Keywords, Labels, Packages, Reserved words, Subprograms, Types,
Variables.
o Literals: A literal is a value that is neither represented by an identifier nor calculated
from other values.
o Comments: The PL/SQL compiler ignores comments. Their purpose is to help other
application developers understand your source text. Typically, you use comments to
describe the purpose and use of each code segment. Comments are two types- Single
Line Comments (--) and Multiline Comments.(/* */)
o Declarations: A declaration allocates storage space for a value of a specified data
type, and names the storage location so that you can reference it.

3. Scope and Visibility of Identifiers


The scope of an identifier is the region of a PL/SQL unit from which you can reference the
identifier. The visibility of an identifier is the region of a PL/SQL unit from which you can
reference the identifier without qualifying it.

4. Expressions
An expression is a combination of one or more values, operators, and SQL functions
that evaluates to a value.
An expression always returns a single value. The simplest expressions, in order of increasing
complexity, are:
o A single constant or variable (for example, a)
o A unary operator and its single operand (for example, -a)
o A binary operator and its two operands (for example, a+b)

8
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

# PL/SQL IDENTIFIERS
Identifiers are used to name PL/SQL program items & units which include: - Constants,
Variables, Exceptions, Cursors, Reserved words.

Rules for naming identifiers


 It must start with a letter optionally followed by more letters, numerals, dollar signs,
underscores, and number signs.
 Other characters such as hyphens, slashes, and spaces are not allowed.
 Any reserved keyword in PL/SQL cannot be used as an identifier
 Identifiers in PL/SQL are not case – sensitive. For e.g. the identifiers lastname,
LastName and LASTNAME are the same.

# PL/SQL Constants
A constant is the name of a memory location which stores a value used in a PL/SQL block
that remains unchanged throughout the program. Similar to a variable a constant also
needs to be declared in the declaration section.
Syntax
constant_name CONSTANT data_type := VALUE;
Example: pi CONSTANT NUMBER (5,4) := 3.1412;

# PL/SQL Comments
Program comments are explanatory statements that can be included in the PL/SQL code
that you write and helps anyone reading its source code. All programming languages allow
some form of comments.
The PL/SQL supports single-line and multi-line comments. All characters available inside
any comment are ignored by the PL/SQL compiler. The PL/SQL single-line comments start
with the delimiter -- (double hyphen) and multi-line comments are enclosed by /* and */.
DECLARE
-- variable declaration
message varchar2(20):= 'Hello, World!';
BEGIN
/*
* PL/SQL executable statement(s)
*/
dbms_output.put_line(message);
END;

9
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

# PL/SQL DATA TYPES


Every PL/SQL constant, variable, parameter, and function return value has a data type
that determines its storage format and its valid values and operations.
Data types in PL/SQL can be divided into:

Scalar Data Types – used to store single


value with no internal components.
Examples:
numeric(inary_float,binary_integer,decimal,flo
at,integer,number, pls_integer, real, smallint,
natural),
character(char,nchar,varchar2, nvarchar2,
long, string), Boolean(true, false, null), &
datetime..

Composite Data Types – used to store values


that have internal components. Examples:
collections and records.

Reference Data Types – used to hold values,


called pointers, used to designate other
program items.
LOB Data Types – use to hold values, called LOB locators that specify the location of large
objects, such as text blocks or graphic images that are stored separately from other
database data.

# PL/SQL Variables
A variable is nothing but a name given to a storage area that our programs can manipulate.
Each variable in PL/SQL has a specific data type, which determines the size and the layout
of the variable's memory; the range of values that can be stored within that memory and
the set of operations that can be applied to the variable. Variable is a placeholders that
store the values that can change through the PL/SQL Block. PL/SQL programming
language allows defining various types of variables, such as date time data types, records,
collections, etc.

The name of a PL/SQL variable consists of a letter optionally followed by more letters,
numerals, dollar signs, underscores, and number signs and should not exceed 30
characters. By default, variable names are not case-sensitive. You cannot use a reserved
PL/SQL keyword as a variable name.
Syntax
variable_name datatype [NOT NULL := value ];

10
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

Example:
DECLARE
salary number (6);
We can directly assign values to variables.
The General Syntax is:
variable_name:= value;
We can assign values to variables directly from the database
DECLARE
var_salary number(6);
var_emp_id number(6) = 1116;
BEGIN
SELECT salary INTO var_salary FROM employee WHERE emp_id =
var_emp_id;
dbms_output.put_line(var_salary);
dbms_output.put_line('The employee ' || var_emp_id || ' has
salary ' || var_salary);
END;

Scope of Variables
PL/SQL allows the nesting of Blocks within Blocks i.e, the Execution section (BEGIN
block) of an outer block can contain inner blocks. Therefore, a variable which is
accessible to an outer Block is also accessible to all nested inner Blocks. The
variables declared in the inner blocks are not accessible to outer blocks. Based on
their declaration we can classify variables into two types.
Local variables - These are declared in an inner block and cannot be referenced by
outside Blocks.
Global variables - These are declared in an outer block and can be referenced by its
itself and by its inner blocks.
DECLARE
-- Global variables
num1 number := 95;
num2 number := 85;
BEGIN
dbms_output.put_line('Outer Variable num1: ' || num1);
dbms_output.put_line('Outer Variable num2: ' || num2);
DECLARE
-- Local variables
num1 number := 195;
num2 number := 185;
BEGIN
dbms_output.put_line('Inner Variable num1: ' || num1);
dbms_output.put_line('Inner Variable num2: ' || num2);
END;
END;

11
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

# PL/SQL - IF-THEN-ELSIF Statement


The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF-
THEN statement can be followed by an optional ELSIF...ELSE statement. The ELSIF clause
lets you add additional conditions.
When using IF-THEN-ELSIF statements there are a few points to keep in mind.
 It's ELSIF, not ELSEIF.
 An IF-THEN statement can have zero or one ELSE's and it must come after any
ELSIF's.
 An IF-THEN statement can have zero to many ELSIF's and they must come before
the ELSE.
 Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's will be tested.

Syntax
IF(boolean_expression 1)THEN
S1; -- Executes when the boolean expression 1 is true
ELSIF( boolean_expression 2) THEN
S2; -- Executes when the boolean expression 2 is true
ELSIF( boolean_expression 3) THEN
S3; -- Executes when the boolean expression 3 is true
ELSE
S4; -- executes when the none of the above condition is true
END IF;

Example
DECLARE
a number(3) := 100;
BEGIN
IF ( a = 10 ) THEN
dbms_output.put_line('Value of a is 10' );
ELSIF ( a = 20 ) THEN
dbms_output.put_line('Value of a is 20' );
ELSIF ( a = 30 ) THEN
dbms_output.put_line('Value of a is 30' );
ELSE
dbms_output.put_line('None of the values is matching');
END IF;
END;

12
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

# PL/SQL - CASE Statement


Like the IF statement, the CASE statement selects one sequence of statements to execute.
However, to select the sequence, the CASE statement uses a selector rather than multiple
Boolean expressions. A selector is an expression, the value of which is used to select one of
several alternatives.
Syntax
CASE selector
When val then
End case

Example
DECLARE
grade char(1) := 'A';
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Well done');
when 'D' then dbms_output.put_line('You passed');
when 'F' then dbms_output.put_line('Better try again');
else
dbms_output.put_line('No such grade');
END CASE;
END;

13
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

# PL/SQL – Loops
A loop statement allows us to execute a statement or group of statements multiple times.
PL/SQL provides the following types of loop to handle the looping requirements. Click the
following links to check their detail.

1. PL/SQL Basic LOOP


In this loop structure, sequence of statements is enclosed between the LOOP and the END
LOOP statements. At each iteration, the sequence of statements is executed and then
control resumes at the top of the loop.

Syntax
LOOP
Sequence of statements;
END LOOP;

Example
DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
IF x > 50 THEN
exit;
END IF;
END LOOP;
dbms_output.put_line('After Exit x is: ' || x);
END;

2. PL/SQL FOR LOOP


A FOR LOOP is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax
FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
END LOOP;
Example:
DECLARE
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;

14
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

3. PL/SQL WHILE LOOP


Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.A WHILE LOOP statement in PL/SQL
programming language repeatedly executes a target statement as long as a given condition
is true.
Syntax
WHILE condition LOOP
sequence_of_statements
END LOOP;

Example
DECLARE
a number(2) := 10;
BEGIN
WHILE a < 20 LOOP
dbms_output.put_line('value of a: ' || a);
a := a + 1;
END LOOP;
END;

4. Nested loops in PL/SQL


PL/SQL allows using one loop inside another loop. Following section shows a few examples
to illustrate the concept.
Syntax
LOOP FOR var IN start .. final LOOP WHILE condition1 LOOP
statements statements1 statements1
LOOP FOR var IN start .. final LOOP WHILE condition2 LOOP
statements statements2 statements2
END LOOP; END LOOP; END LOOP;
END LOOP; END LOOP; END LOOP;

Example
The following program uses a nested basic loop to find the prime numbers from 2 to 50
DECLARE
i number(3);
j number(3);
BEGIN
i := 2;
LOOP
j:= 2;
LOOP
exit WHEN ((mod(i, j) = 0) or (j = i));
j := j +1;
END LOOP;

15
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103
IF (j = i ) THEN
dbms_output.put_line(i || ' is prime');
END IF;
i := i + 1;
exit WHEN i = 50;
END LOOP;
END;

# The Loop Control Statements


Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed. PL/SQL
supports the following control statements.

1. EXIT statement
The Exit statement completes the loop and control passes to the statement immediately
after the END LOOP.
There are two syntax of exit.
a. Exit;
While a < 20 LOOP
dbms_output.put_line ('value of a: ' || a);
a := a + 1;
IF a > 15 THEN
EXIT;
END IF;
END LOOP;

b. Exit when condition ;


WHILE a < 20 LOOP
dbms_output.put_line ('value of a: ' || a);
a := a + 1;
EXIT WHEN a > 15;
END LOOP;

2. CONTINUE statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating.
While a < 10 LOOP
a := a + 1;
IF a = 5 THEN
continue;
END IF;
dbms_output.put_line ('value of a: ' || a);
END LOOP;

16
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

# PL/SQL – Subprogram
A subprogram is a program unit/module that performs a particular task. These
subprograms are combined to form larger programs. This is basically called the 'Modular
design'. A subprogram can be invoked by another subprogram or program which is called
the calling program.
PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of
parameters. PL/SQL provides two kinds of subprograms −

 Functions − These subprograms return a single value; mainly used to compute and
return a value.
 Procedures − These subprograms do not return a value directly; mainly used to
perform an action.

# PL/SQL – Procedure
These subprograms do not return a value directly; mainly used to perform an action. The
PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or
more specific tasks. It is just like procedures in other programming languages.
The procedure contains a header and a body.
o Header: The header contains the name of the procedure and the parameters or
variables passed to the procedure.
o Body: The body contains a declaration section, execution section and exception
section similar to a general PL/SQL block.
How to pass parameters in procedure:
When you want to create a procedure or function, you have to define parameters .There is
three ways to pass parameters in procedure:
1. IN parameters: The IN parameter can be referenced by the procedure or function.
The value of the parameter cannot be overwritten by the procedure or the function.
2. OUT parameters: The OUT parameter cannot be referenced by the procedure or
function, but the value of the parameter can be overwritten by the procedure or
function.
3. INOUT parameters: The INOUT parameter can be referenced by the procedure or
function and the value of the parameter can be overwritten by the procedure or
function.

Executing a Procedure
A standalone procedure can be called in two ways −
 Using the EXECUTE keyword
 Calling the name of the procedure from a PL/SQL block

17
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

Syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])] {IS | AS}
BEGIN
< procedure_body >
END procedure_name;
Example 1:
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
----------------------
EXECUTE greetings;
Or
BEGIN
greetings;
END;
----------------------

Example 2:
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;

18
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

# PL/SQL – Functions
A function is same as a procedure except that it returns a value. The function header has
the function name and a RETURN clause that specifies the data type of the returned value.
Each parameter of the function can be either in the IN, OUT, or INOUT mode.

The function body is the same as the procedure body which has three sections: declarative
section, executable section, and exception-handling section.

 The declarative section is between the IS and BEGIN keywords. It is where you
declare variables, constants, cursors, and user-defined types.
 The executable section is between the BEGIN and END keywords. It is where you
place the executable statements. Unlike a procedure, you must have at least
one RETURN statement in the executable statement.
 The exception-handling section is where you put the exception handler code.

Syntax to create a function:


CREATE [OR REPLACE] FUNCTION function_name [parameters]
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype {IS | AS}
BEGIN
< function_body >
END [function_name];
Example:
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number IS z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;

BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;

19
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

# PL/SQL - Cursors
A cursor is a pointer to this context area. PL/SQL controls the context area through a
cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of rows
the cursor holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process the
rows returned by the SQL statement, one at a time. There are two types of cursors −
 Implicit cursors
 Explicit cursors

Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed, when there is no explicit cursor for the statement. Programmers cannot
control the implicit cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit
cursor is associated with this statement. For INSERT operations, the cursor holds the
data that needs to be inserted. For UPDATE and DELETE operations, the cursor
identifies the rows that would be affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which
always has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT.
The SQL cursor has additional attributes, %BULK_ROWCOUNT and
%BULK_EXCEPTIONS, designed for use with the FORALL statement. The following table
provides the description of the most used attributes −
S.No Attribute & Description

%FOUND
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one
1
or more rows or a SELECT INTO statement returned one or more rows.
Otherwise, it returns FALSE.

%NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE,
2
or DELETE statement affected no rows, or a SELECT INTO statement
returned no rows. Otherwise, it returns FALSE.

%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL
cursor automatically after executing its associated SQL statement.

%ROWCOUNT
4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE
statement, or returned by a SELECT INTO statement.

20
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in


the example.
Example: We will be using the CUSTOMERS table.
Select * from customers;
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00

The following program will update the table and increase the salary of each customer
by 500 and use the SQL%ROWCOUNT attribute to determine the number of rows
affected −
DECLARE
total_rows number(2);
BEGIN
UPDATE customers SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;

When the above code is executed at the SQL prompt, it produces the following result
− 6 customers selected, PL/SQL procedure successfully completed.
If you check the records in customers table, you will find that the rows have been
updated −
Select * from customers;
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2500.00
2 Khilan 25 Delhi 2000.00
3 kaushik 23 Kota 2500.00
4 Chaitali 25 Mumbai 7000.00
5 Hardik 27 Bhopal 9000.00
6 Komal 22 MP 5000.00

21
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over
the context area. An explicit cursor should be defined in the declaration section of
the PL/SQL Block. It is created on a SELECT Statement which returns more than
one row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;

Working with an explicit cursor includes the following steps −


 Declaring the cursor for initializing the memory
 Opening the cursor for allocating the memory
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory

Declaring the Cursor


Declaring the cursor defines the cursor with a name and the associated SELECT
statement. For example −
CURSOR c_customers IS SELECT id, name, address FROM customers;

Opening the Cursor


Opening the cursor allocates the memory for the cursor and makes it ready for
fetching the rows returned by the SQL statement into it. For example, we will open
the above defined cursor as follows −
OPEN c_customers;

Fetching the Cursor


Fetching the cursor involves accessing one row at a time. For example, we will fetch
rows from the above-opened cursor as follows −
FETCH c_customers INTO c_id, c_name, c_addr;

Closing the Cursor


Closing the cursor means releasing the allocated memory. For example, we will close
the above-opened cursor as follows −
CLOSE c_customers;
Example
Following is a complete example to illustrate the concepts of explicit cursors &minua;
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is SELECT id, name, address FROM customers;
BEGIN

22
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103

OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
When the above code is executed at the SQL prompt, it produces the following result −
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP

PL/SQL procedure successfully completed.

23

You might also like