PL-SQL
PL-SQL
This section starts with the keyword DECLARE. It is an optional section and defines all variables,
cursors, subprograms, and other elements to be used in the program.
Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It
consists of the executable PL/SQL statements of the program. It should have at least one executable
line of code, which may be just a NULL command to indicate that nothing should be executed.
Exception Handling
This section starts with the keyword EXCEPTION. This optional section contains exception(s) that
handle errors in the program.
DECLARE
<declarations section>
BEGIN <executable command(s)>
EXCEPTION <exception handling> END;
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
% Attribute indicator
. Component selector
, Item separator
= Relational operator
; Statement terminator
:= Assignment operator
|| Concatenation operator
** Exponentiation operator
Scalar
Single values with no internal components, such as a NUMBER,
DATE, or BOOLEAN
Composite
Data items that have internal components that can be accessed
individually. For example, collections and records.
Reference
Pointers to other data items.
Variable Declaration in PL/SQL
variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]
DECLARE
Initializing Variables in PL/SQL :
a integer := 10;
b integer := 20;
The DEFAULT keyword
c integer;
The assignment operator
f real;
Example:
BEGIN
a:=0;
c := a + b;
B Varchar2(10) DEFAULT ‘Good Morning’
dbms_output.put_line('Value of c: ' || c);
f := 70.0/3.0;
dbms_output.put_line('Value of f: ' || f);
END;
Variable Scope in PL/SQL
• Local variables − Variables declared in an inner block and not accessible
to outer blocks.
• Global variables − Variables declared in the outermost block or a
package. 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;
PL/SQL - Operators
• Arithmetic operators
• Relational operators
• Comparison operators
• Logical operators
• String operators
Arithmetic Operators
Operator Description Example
+ Adds two operands A + B will give 15
- Subtracts second operand A - B will give 5
from the first
• IF-THEN
• IF-THEN-ELSE statement
IF condition
THEN S1;
ELSE S2;
END IF;
Syntax
DECLARE
WHILE condition LOOP
a number(2) := 10;
sequence_of_statements
BEGIN
END LOOP;
WHILE a < 20 LOOP
dbms_output.put_line('value of a: ' || a);
a := a + 1;
END LOOP;
END;
FOR LOOP
Syntax
FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
DECLARE
END LOOP;
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
VARRAY
• Which can store a fixed-size sequential collection of elements of the
same type.
• All varrays consist of contiguous memory locations.
• The lowest address corresponds to the first element and the highest
address to the last element.
Creating a Varray Type
• A varray type is created with the CREATE TYPE statement.
• You must specify the maximum size and the type of elements stored in the
varray.
• The basic syntax for creating a VARRAY type within a PL/SQL block is −
• For example −
TYPE namearray IS VARRAY(5) OF VARCHAR2(10);
Type grades IS VARRAY(5) OF INTEGER;
• Example:
DECLARE
type namesarray IS VARRAY(5) OF VARCHAR2(10);
type grades IS VARRAY(5) OF INTEGER; Output:
names namesarray;
marks grades; Total 5 Students
total integer;
Student: Kavita Marks: 98
BEGIN
names := namesarray('Kavita', 'Pritam', 'Ayan', 'Rishav', 'Aziz'); Student: Pritam Marks: 97
marks:= grades(98, 97, 78, 87, 92);
total := names.count; Student: Ayan Marks: 78
dbms_output.put_line('Total '|| total || ' Students');
Student: Rishav Marks: 87
FOR i in 1 .. total LOOP
dbms_output.put_line('Student: ' || names(i) || ' Marks: ' || marks(i)); Student: Aziz Marks: 92
END LOOP;
END;
PL/SQL - Procedures
• 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.
Declarative Part
• It is an optional part. However, the declarative part for a subprogram does not start with the DECLARE
keyword.
• It contains declarations of types, cursors, constants, variables, exceptions, and nested subprograms.
• These items are local to the subprogram and cease to exist when the subprogram completes execution.
Executable Part
• This is a mandatory part and contains statements that perform the designated action.
Exception-handling
• This is again an optional part. It contains the code that handles run-time errors.
Creating a Procedure
• The simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows--
BEGIN
END procedure_name;
• procedure-name specifies the name of the procedure.
• The optional parameter list contains name, mode and types of the parameters.
• IN represents the value that will be passed from outside and OUT represents
the parameter that will be used to return a value outside of the procedure.
AS
BEGIN
dbms_output.put_line(‘hai');
END;
Executing a Procedure
OUT
An OUT parameter returns a value to the calling program. Inside the subprogram, an OUT parameter acts like a variable.
You can change its value and reference the value after assigning it. The actual parameter must be variable and it is
passed by value.
IN OUT
An IN OUT parameter passes an initial value to a subprogram and returns an updated value to the caller. It can be
assigned a value and the value can be read.
The actual parameter corresponding to an IN OUT formal parameter must be a variable, not a constant or an expression.
Formal parameter must be assigned a value. Actual parameter is passed by value.
IN & OUT Mode Example
• This program finds the minimum of two values. Here, the procedure takes two numbers using the IN mode and returns their minimum using the OUT
parameters.
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) OUTPUT: Minimum of (23, 45) : 23
IS
PL/SQL procedure successfully completed.
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);
Methods for Passing Parameters
DECLARE
num number;
factorial number;
FUNCTION fact(x number)
RETURN number IS f number;
BEGIN
IF x=0 THEN
f := 1;
ELSE f := x * fact(x-1);
END IF;
RETURN f;
END;
BEGIN
num:= 6;
factorial := fact(num);
O N;
dbms_output.put_line(' Factorial '|| num || ' is ' || factorial); P UT
O UT
END;
VER
SER
OUTPUT: SET
Factorial 5 is 120
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
• 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.
Attribute & Description
%FOUND
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one 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, or DELETE
statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it
returns FALSE.
%ISOPEN
Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically
after executing its associated SQL statement.
%ROWCOUNT
Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or
returned by a SELECT INTO statement.
• CUSTOMERS table we had created.
CURSOR c_customers IS
SELECT id, name, address FROM customers;
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 fetch rows from the above-opened cursor as follows −
CLOSE c_customers;
DECLARE
c_id customers.id%type; 1 Ramesh Ahmedabad
c_name customers.name%type;
c_addr customers.address%type; 2 Ravi Delhi
CURSOR c_customers is
SELECT id, name, address FROM customers; 3 kumar Kota
BEGIN OPEN c_customers;
LOOP 4 Sai Mumbai
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound; 5Ram Bhopal
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP; 6 SitaMP
CLOSE c_customers;
END;