PL/SQL
Introduction
• PL/SQL is a sophisticated programming language used to
access an Oracle database from various environments.
• It is an extension to non-procedural language SQL.
• It combines the data manipulation power of SQL with
the data processing power of procedural language.
Introduction
• Oracle provides PL/SQL or Procedural SQL, which
can be used to create programs for validation and
manipulation of data.
• With PL/SQL, we can insert, update, delete and query
the data, as well as we can use procedural techniques
such as writing loops or branching to another block of
data.
• PL/SQL block can contain any number of SQL
statements. It allows us to logically group a number
of SQL statements and pass them to Oracle as a
single block.
Advantages
Better Performance: Most of the database applications
are based on client-server model.
• In this model, application program resides on the client
machine and sends requests to the database server for
processing. These requests are SQL requests.
• Typically, this results in many network trips, one for each
SQL statements. This slows down the data processing
considerably specially when several users are firing SQL
statements at the same time.
• But if we are bundling these statements in a single unit and
then sending this to the server, results to the less network
and faster application.
Advantages
Advantages
Object Oriented support: Object oriented
Programming is used to reduce cost and time for
developing applications.
• It provides features such as information hiding
and data encapsulation. The object-oriented
features are supported by packages and object
data types.
Portability: Since PL/SQL is native to Oracle;
programs may be transported across any host
environment in which Oracle and PL/SQL are
supported.
Advantages
High Productivity: PL/SQL can be used to
include procedural constructs in non-procedural
tool like Developer/2000 FORMS and REPORTS.
Support for SQL: PL/SQL allows us to use all
SQL data manipulation commands, transactions
control commands, SQL functions (except group
function), operators, thus allowing us to
manipulate data values in a table with more
flexibility and efficiently.
Advantages
Integration with Oracle: PL/SQL is playing an
increasing central role in both the RDBMS (stored
procedures, functions, triggers and packages)
and in Oracle tools (Developer/2000 Forms,
reports etc.).
The variables and data types of PL/SQL are
compatible with those of SQL. PL/SQL, therefore,
bridges the gap between convenient access to
database technology and the need for
procedural programming language capabilities.
Structure of PL/SQL Program
• PL/SQL is a block structured language. Each
block is supposed to perform one logical unit of
job. These blocks may be entirely separate, or
nested one within another.
• Each block is having three section: a declare
section, an executable section and an exception
handling section.
Block Structure of PL/SQL Program
DECLARE
Declaration of memory variables, constants, cursor
etc. in PL/SQL
BEGIN
SQL Executable section
PL/SQL Executable section
EXCEPTION
Exception Handler – What to do if the executable
actions cause an error condition.
END
Block Structure of PL/SQL Program
• The BEGIN and END elements are main, and body of
the actions to be performed, is enclosed in between
BEGIN and END.
• The DECLARE section is optional and used to define
PL/ SQL objects.
• Finally the EXCEPTION section is used to trap the
error conditions and define actions to be obeyed, if
such a specified condition occurs. The EXCEPTION
section is also optional and is placed immediately
before the END.
Block Structure of PL/SQL Program
• Note that the section keywords DECLARE,
BEGIN and EXCEPTION are not followed by
semi-colons (;) but the END and all other
PL/SQL statements must have the semi-colons
at their end.
Variable Declaration
• PL/SQL enforces the declaration of variables
before their use in executable portion.
• All the variables or constants have to be
declared before their use.
• A variable can be declared as:
variable_name variable_datatype;
• variable_datatype is any valid SQL data type
such as CHAR, DATE and NUMBER or PL/SQL
data type such as composite data types.
Example: x NUMBER (7, 2)
Variable Declaration
• We can also declare a variable as composite
data type by using %TYPE or %ROWTYPE
attributes.
• %TYPE: It provides data type information of a
column or variable.
• For example: x [Link]%TYPE;
Here, a variable x having the same data type as
Sal column of EMP table.
Variable Declaration
• %ROWTYPE:- PL/SQL record is used to store
information that is related and consists of
different data types. For example emp_rec is a
variable, which holds the value of one row of
EMP table it can be declared as
emp_rec EMP%ROWTYPE;
• It declares a variable emp_rec as record. The
fields of emp_rec are having the same name as
columns of EMP table and can be called by using
the (.) notation like emp_rec. Empno or
emp_rec.Ename, where Empno and Ename are
the columns of EMP table.
Variable Declaration
• We can assign the values to the variables
using the assignment operator (:=) in the
Declare section as:
• x NUMBER (4) := 300;
• d_birth DATE := ’10-DEC-97’;
•y [Link]%type := x * 4.5;
CONSTANT Declaration
• We can declare constants in the declarative
part and can use them elsewhere in the
executable part, like any variable.
• To declare a constant, we must make use of the
keyword constant.
• This keyword must precede the data type as
shown below:
• creditlimit CONSTANT NUMBER (4) := 5000;
Example
DECLARE
var_num1 number;
var_num2 number;
BEGIN
var_num1 := 100;
var_num2 := 200;
var_num1:= var_num1 * var_num2;
DBMS_OUTPUT.PUT_LINE(var_num1);
END;
To Display a message
• DBMS_OUTPUT.PUT_LINE (‘Welcome to the
World of PL/SQL’);
• dbms_output is a package that includes a
number of procedures and functions that
accumulate information in a buffer so that it can
be retrieved later.
Control Constructs
• The use of control constructs is to control the
processing flow of its code.
• The conditional statements, branches and loops in the
PL/SQL programs are used for the control of flow of
statements.
• These constructs can be divided into following
categories.
(i) Conditional Control Statement: These are of three
types:
IF…END IF
IF…ELSE…ENDIF
IF…ELSEIF..ELSEIF…ELSE…END IF
Control Constructs
• (ii) Iterative Statement: These are of three
types
WHILE…LOOP…END LOOP
FOR…LOOP…END LOOP
LOOP…EXIT…END LOOP
• (iii) Unconditional Branching
GOTO
Conditional Statements
• IF statement is used to change the flow of
program conditionally.
• The IF clause specifies the condition, while
THEN clause defines the set of actions, which
are done if the condition if TRUE, and ELSE
part causes to perform actions if condition is
FALSE.
Conditional Statements
The syntax for various IF statements are
a. IF <condition> THEN
Actions to be performed if condition is TRUE
END IF;
b. IF <condition>THEN
Actions to be performed if condition is TRUE
ELSE
Actions to be performed if condition is FALSE
END IF;
Conditional Statements
IF <condition>THEN
Actions to be performed if condition 1 is TRUE
ELSEIF <condition2> THEN
Actions to be performed if condition 2 is TRUE and
condition 1 is FALSE
ELSEIF <condition3> THEN
Actions to be performed if condition 3 IS TRUE and condition 1
and condition 2 are FALSE
……
ELSE
Actions to be performed if all the above conditions are
FALSE
END IF;
Conditional Statements
DECLARE
a number(3) := 100;
BEGIN
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ' );
ELSE
dbms_output.put_line('a is not less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
Iterative Statement
Iterative statements are used to execute some
statements repeatedly. The repetitions can be
controlled in two ways:
• to repeat a code for a specified number of times.
• to repeat the code until some condition is met,
thus rendering a comparison operator to TRUE.
Iterative Statement
• There are three types of iterative statements
1. LOOP-EXIT Statement
• This is the simplest kind of PL/SQL loop. The
LOOP…END LOOP provides infinite loops.
• This loop will execute infinitely since this loop has
no stopping condition.
• To terminate loop, EXIT statement is used.
LOOP-EXIT Statement
DECLARE
x NUMBER;
BEGIN
x := 0;
LOOP
x := x + 2;
DBMS_OUTPUT.PUT_LINE (x);
EXIT WHEN x = 20;
END LOOP;
END;
Iterative Statement
• WHILE –LOOP Statement:
• In a while-loop statement, the exiting condition is
evaluated at the beginning of the statement, while
in the loop-exit statement, the exit condition is
evaluated wherever is the exit when statement is
placed.
• The syntax for a while-loop is as follow:
WHILE <condition> LOOP
Sequence of statements;
END LOOP;
WHILE –LOOP Statement
• The condition is evaluated before each
iteration of the loop.
• If it evaluates to TRUE, sequence of statements
is executed and control goes to the top of the
loop but if it evaluates to FALSE or NULL then
the loop is finished and control resumes after
the END LOOP statement.
• The exit or exit-when statement can still be
used inside a while-loop to exit the loop
prematurely, if desired.
WHILE –LOOP Statement
DECLARE
x NUMBER(2);
BEGIN
x := 0;
WHILE x < = 20 LOOP
x := x + 2;
DBMS_OUTPUT.PUT_LINE (x);
END LOOP;
END;
FOR –LOOP Statement
• The FOR LOOP allows the user to specify exactly the
number of times the code will execute before
PL/SQL will break out of it.
• To accomplish this task, the for-loop statement
specifies a loop counter and a range through which
the counter will circulate. The loop counter can be in
reverse order also.
Syntax:
• FOR loop_counter IN lower_limit..upper_limit LOOP
Sequence of statements;
END LOOP;
FOR –LOOP Statement
Example: To print a table of 2.
DECLARE
x NUMBER(2);
BEGIN
FOR i IN 1 ..10 LOOP
x := 2 * i;
DBMS_OUTPUT.PUT_LINE(x);
END LOOP;
END
FOR –LOOP Statement
• If the REVERSE keyword is present in the FOR loop then the
loop_counter will iterate from the upper_limit to the
lower_limit.
• Example: To print a table of 2 (In reverse).
DECLARE
x NUMBER;
BEGIN
FOR i IN REVERSE 1..10 LOOP
x := 2 * i;
DBMS_OUTPUT.PUT_LINE(x);
END LOOP;
END;
FOR –LOOP Statement
• Any expression can be converted to a numeric value. For
example:
DECLARE
lower_limit NUMBER(2);
Higher_limit NUMBER(2);
x NUMBER(2);
BEGIN
lower_limit := 1;
higher_limit := 10;
FOR i IN lower_limit..higher_limit LOOP
x := 2 * i;
DBMS_OUTPUT.PUT_LINE (x);
END LOOP;
END;
GOTO Statements
• GOTO statements are used for unconditional
branching.
• The user should avoid the use of GOTO because it
results in complex and unstructured code.
• It is recommended to use exception rather than
GOTO to branch from deep nested structure.
• The code for summing 100 numbers using GOTO
statement is shown as example in next slide.
• If the value of i is less than or equal to 100 then
control transfer the control to statement having label
abc. The label should be unique in the scope and must
precede an executable statement in the block.
GOTO Statements
DECLARE
i NUMBER(2);
s NUMBER(2);
BEGIN
i :=0;
s :=0;
<<abc>>
s := s + i;
i := i + 1;
IF i <=100 THEN
GOTO abc;
END IF;
DBMS_OUTPUT.PUT_LINE(s);
END;