0% found this document useful (0 votes)
2 views38 pages

Rdbms Unit-III PL-SQL

PL/SQL (Procedural Language/Structured Query Language) is a block-structured language developed by Oracle that combines SQL with procedural programming constructs, enabling efficient data manipulation and control-flow logic within the Oracle Database. It includes features such as exception handling, the ability to execute multiple queries in one block, and supports various data types and identifiers. PL/SQL programs are structured in blocks, which consist of declaration, execution, and optional exception sections, allowing for complex application development.

Uploaded by

anannyaaravi
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)
2 views38 pages

Rdbms Unit-III PL-SQL

PL/SQL (Procedural Language/Structured Query Language) is a block-structured language developed by Oracle that combines SQL with procedural programming constructs, enabling efficient data manipulation and control-flow logic within the Oracle Database. It includes features such as exception handling, the ability to execute multiple queries in one block, and supports various data types and identifiers. PL/SQL programs are structured in blocks, which consist of declaration, execution, and optional exception sections, allowing for complex application development.

Uploaded by

anannyaaravi
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

UNIT-III

INTRODUCTION TO PL/SQL:

PL/SQL (Procedural Language/Structured Query Language) is a block-structured


language developed by Oracle that allows developers to combine the power
of SQL with procedural programming constructs. The PL/SQL language enables
efficient data manipulation and control-flow logic, all within the Oracle Database.
Basics of PL/SQL
● PL/SQL stands for Procedural Language extensions to the Structured Query
Language (SQL).
● PL/SQL is a combination of SQL along with the procedural features of
programming languages.
● Oracle uses a PL/SQL engine to process the PL/SQL statements.
● PL/SQL includes procedural language elements like conditions and loops. It
allows declaration of constants and variables, procedures and functions, types
and variable of those types and triggers.
Features of PL/SQL
1. PL/SQL is basically a procedural language, which provides the functionality of
decision-making, iteration, and many more features of procedural
programming languages.
2. PL/SQL can execute a number of queries in one block using single command.
3. One can create a PL/SQL unit such as procedures, functions, packages, triggers,
and types, which are stored in the database for reuse by applications.
4. PL/SQL provides a feature to handle the exception which occurs in PL/SQL block
known as exception handling block.
5. Applications written in PL/SQL are portable to computer hardware or operating
system where Oracle is operational.
6. PL/SQL Offers extensive error checking.

Differences Between SQL and PL/SQL

SQL PL/SQL

PL/SQL is a block of codes that used to


SQL is a single query that is used to
write the entire program blocks/
perform DML and DDL operations.
procedure/ function, etc.
SQL PL/SQL

It is declarative, that defines what


PL/SQL is procedural that defines how
needs to be done, rather than how
the things needs to be done.
things need to be done.

Execute as a single statement. Execute as a whole block.

Mainly used to manipulate data. Mainly used to create an application.

It is an extension of SQL, so it can


Cannot contain PL/SQL code in it.
contain SQL inside it.

Structure of PL/SQL Block:


PL/SQL extends SQL by adding constructs found in procedural languages,
resulting in a structural language that is more powerful than SQL. The basic unit in
PL/SQL is a block. All PL/SQL programs are made up of blocks, which can be
nested within each other.

Typically, each block performs a logical action in the program. A block has the
following structure:
● Declare section starts with DECLARE keyword in which variables, constants,
records as cursors can be declared which stores data temporarily. It basically
consists definition of PL/SQL identifiers. This part of the code is optional.
● Execution section starts with BEGIN and ends with END keyword. This is a
mandatory section and here the program logic is written to perform any task
like loops and conditional statements. It supports
all DML commands, DDL commands and SQL*PLUS built-in functions as well.
● Exception section starts with EXCEPTION keyword. This section is optional
which contains statements that are executed when a run-time error occurs. Any
exceptions can be handled in this section.
PL/SQL Identifiers:
There are several PL/SQL identifiers such as variables, constants, procedures,
cursors, triggers.
1. Variables: Like several other programming languages, variables in PL/SQL must
be declared prior to its use. They should have a valid name and data type as
well. Syntax for declaration of variables:

[Link] to show how to declare variables in PL/SQL :

SQL> SET SERVEROUTPUT ON;

SQL> DECLARE
var1 INTEGER;
var2 REAL;
var3 varchar2(20) ;

BEGIN
null;
END;
/
Output:
PL/SQL procedure successfully completed.
Explanation:
● SET SERVEROUTPUT ON: It is used to display the buffer used by the
dbms_output.
● var1 INTEGER : It is the declaration of variable, named var1 which is of
integer type. There are many other data types that can be used like float, int,
real, smallint, long etc. It also supports variables used in SQL as well like
NUMBER(prec, scale), varchar, varchar2 etc.
● PL/SQL procedure successfully completed.: It is displayed when the code is
compiled and executed successfully.
● Slash (/) after END;: The slash (/) tells the SQL*Plus to execute the block.
● Assignment operator (:=) : It is used to assign a value to a variable.
Displaying Output: The outputs are displayed by using DBMS_OUTPUT which is a
built-in package that enables the user to display output, debugging information,
and send messages from PL/SQL blocks, subprograms, packages, and triggers. Let
us see an example to see how to display a message using PL/SQL :
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
var varchar2(40) := 'I love GeeksForGeeks' ;

BEGIN
dbms_output.put_line(var);

END;
/
Output:
I love GeeksForGeeks
PL/SQL procedure successfully completed.

Explanation:
● dbms_output.put_line : This command is used to direct the PL/SQL output to
a screen.
2. Using Comments: Like in many other programming languages, in PL/SQL also,
comments can be put within the code which has no effect in the code. There
are two syntaxes to create comments in PL/SQL :
● Single Line Comment: To create a single line comment , the symbol – – is
used.
● Multi Line Comment: To create comments that span over several lines, the
symbol /* and */ is used.
3. Taking input from user: Just like in other programming languages, in PL/SQL
also, we can take input from the user and store it in a variable. Let us see an
example to show how to take input from users in PL/SQL:
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
-- taking input for variable a
a number := &a;
-- taking input for variable b
b varchar2(30) := &b;
BEGIN
null;
END;
/
1. Output:
Enter value for a: 24
old 2: a number := &a;
new 2: a number := 24;
Enter value for b: 'GeeksForGeeks'
old 3: b varchar2(30) := &b;
new 3: b varchar2(30) := 'GeeksForGeeks';

PL/SQL procedure successfully completed.

(***) Let us see an example on PL/SQL to demonstrate all above concepts in one
single block of code.
--PL/SQL code to print sum of two numbers taken from the user.
SQL> SET SERVEROUTPUT ON;

SQL> DECLARE
-- taking input for variable a
a integer := &a ;
-- taking input for variable b
b integer := &b ;
c integer ;
BEGIN
c := a + b ;
dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c);
END;
/
Enter value for a: 2
Enter value for b: 3
Sum of 2 and 3 is = 5
PL/SQL procedure successfully completed.

PL/SQL Execution Environment:


The PL/SQL engine resides in the Oracle engine. The Oracle engine can process not
only single SQL statement but also block of many statements. The call to Oracle
engine needs to be made only once to execute any number of SQL statements if
these SQL statements are bundled inside a PL/SQL block.
Advantages of PL/SQL:
● SQL is the standard database language and PL/SQL is strongly integrated with SQL.
PL/SQL supports both static and dynamic SQL. Static SQL supports DML operations
and transaction control from PL/SQL block. In Dynamic SQL, SQL allows embedding
DDL statements in PL/SQL blocks.
● PL/SQL allows sending an entire block of statements to the database at one time.
This reduces network traffic and provides high performance for the applications.
● PL/SQL gives high productivity to programmers as it can query, transform, and
update data in a database.
● PL/SQL saves time on design and debugging by strong features, such as exception
handling, encapsulation, data hiding, and object-oriented data types.
● Applications written in PL/SQL are fully portable.
● PL/SQL provides high security level.
● PL/SQL provides access to predefined SQL packages.
● PL/SQL provides support for Object-Oriented Programming.
● PL/SQL provides support for developing Web Applications and Server Pages.

The 'Hello World' Example


DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
The end; line signals the end of the PL/SQL block. To run the code from the SQL command line,
you may need to type / at the beginning of the first blank line after the last line of the code.
When the above code is executed at the SQL prompt, it produces the following result –

Output:

Hello World
PL/SQL procedure successfully completed.

PL/SQL Identifiers

PL/SQL identifiers are constants, variables, exceptions, procedures, cursors, and


reserved words. The identifiers consist of a letter optionally followed by more
letters, numerals, dollar signs, underscores, and number signs and should not
exceed 30 characters.

By default, identifiers are not case-sensitive. So you can use integer or INTEGER to
represent a numeric value. You cannot use a reserved keyword as an identifier.

Delimiters:

A delimiter is a symbol with a special meaning. Following is the list of delimiters in PL/SQL –
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 */.

PL/SQL Program Units

A PL/SQL unit is any one of the following −


● PL/SQL block
● Function
● Package
● Package body
● Procedure
● Trigger
● Type
● Type body

PL/SQL Datatypes:

The PL/SQL variables, constants and parameters must have a valid data type, which specifies a
storage format, constraints, and a valid range of values.

[Link] Category & Description

Scalar
1 Single values with no internal components, such as a NUMBER,
DATE, or BOOLEAN.

Large Object (LOB)


2 Pointers to large objects that are stored separately from other data items, such as
text, graphic images, video clips, and sound waveforms.

Composite
3 Data items that have internal components that can be accessed individually. For
example, collections and records.

4 Reference
Pointers to other data items.

PL/SQL Scalar Data Types and Subtypes


PL/SQL Scalar Data Types and Subtypes come under the following categories −

[Link] Date Type & Description

1 Numeric
Numeric values on which arithmetic operations are performed.

2 Character
Alphanumeric values that represent single characters or strings of characters.

3 Boolean
Logical values on which logical operations are performed.

4 Datetime
Dates and times.
PL/SQL provides subtypes of data types. For example, the data type NUMBER has a subtype
called INTEGER. You can use the subtypes in your PL/SQL program to make the data types
compatible with data types in other programs while embedding the PL/SQL code in another
program, such as a Java program.

PL/SQL Numeric Data Types and Subtypes


Following table lists out the PL/SQL pre-defined numeric data types and their sub-types −

[Link] Data Type & Description

PLS_INTEGER
1 Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32
bits

BINARY_INTEGER
2 Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32
bits

BINARY_FLOAT
3
Single-precision IEEE 754-format floating-point number

BINARY_DOUBLE
4
Double-precision IEEE 754-format floating-point number

NUMBER(prec, scale)
5 Fixed-point or floating-point number with absolute value in range 1E-130 to (but
not including) 1.0E126. A NUMBER variable can also represent 0

DEC(prec, scale)
6
ANSI specific fixed-point type with maximum precision of 38 decimal digits

DECIMAL(prec, scale)
7
IBM specific fixed-point type with maximum precision of 38 decimal digits

NUMERIC(pre, secale)
8
Floating type with maximum precision of 38 decimal digits

DOUBLE PRECISION
9 ANSI specific floating-point type with maximum precision of 126 binary digits
(approximately 38 decimal digits)

FLOAT
10 ANSI and IBM specific floating-point type with maximum precision of 126
binary digits (approximately 38 decimal digits)

INT
11
ANSI specific integer type with maximum precision of 38 decimal digits

INTEGER
12
ANSI and IBM specific integer type with maximum precision of 38 decimal digits

SMALLINT
13
ANSI and IBM specific integer type with maximum precision of 38 decimal digits

REAL
14 Floating-point type with maximum precision of 63 binary digits (approximately
18 decimal digits)

Following is a valid declaration −


When the above code is compiled and executed, it produces the following result –

PL/SQL Character Data Types and Subtypes


Following is the detail of PL/SQL pre-defined character data types and their sub-types −

[Link] Data Type & Description

CHAR
1
Fixed-length character string with maximum size of 32,767 bytes

VARCHAR2
2
Variable-length character string with maximum size of 32,767 bytes

RAW
3 Variable-length binary or byte string with maximum size of 32,767 bytes, not
interpreted by PL/SQL

NCHAR
4
Fixed-length national character string with maximum size of 32,767 bytes

NVARCHAR2
5
Variable-length national character string with maximum size of 32,767 bytes

LONG
6
Variable-length character string with maximum size of 32,760 bytes

LONG RAW
7 Variable-length binary or byte string with maximum size of 32,760 bytes, not
interpreted by PL/SQL

ROWID
8
Physical row identifier, the address of a row in an ordinary table

UROWID
9
Universal row identifier (physical, logical, or foreign row identifier)

PL/SQL Boolean Data Types


The BOOLEAN data type stores logical values that are used in logical operations. The logical values
are the Boolean values TRUE and FALSE and the value NULL.

However, SQL has no data type equivalent to BOOLEAN. Therefore, Boolean values cannot be used
in −

● SQL statements
● Built-in SQL functions (such as TO_CHAR)
● PL/SQL functions invoked from SQL statements

PL/SQL Datetime and Interval Types


The DATE datatype is used to store fixed-length datetimes, which include the time of day in
seconds since midnight. Valid dates range from January 1, 4712 BC to December 31, 9999 AD.

The default date format is set by the Oracle initialization parameter NLS_DATE_FORMAT. For
example, the default might be 'DD-MON-YY', which includes a two-digit number for the day of the
month, an abbreviation of the month name, and the last two digits of the year. For example, 01-
OCT-12.
Each DATE includes the century, year, month, day, hour, minute, and second. The following table
shows the valid values for each field −

PL/SQL Large Object (LOB) Data Types


Large Object (LOB) data types refer to large data items such as text, graphic images, video clips,
and sound waveforms. LOB data types allow efficient, random, piecewise access to this data.
Following are the predefined PL/SQL LOB data types −

PL/SQL User-Defined Subtypes


A subtype is a subset of another data type, which is called its base type. A subtype has the
same valid operations as its base type, but only a subset of its valid values.

PL/SQL predefines several subtypes in package STANDARD. For example, PL/SQL predefines the
subtypes CHARACTER and INTEGER as follows −

SUBTYPE CHARACTER IS CHAR;


SUBTYPE INTEGER IS NUMBER(38,0);
You can define and use your own subtypes. The following program illustrates defining and
using a user-defined subtype −

NULLs in PL/SQL
PL/SQL NULL values represent missing or unknown data and they are not an integer, a character,
or any other specific data type. Note that NULL is not the same as an empty data string or the
null character value '\0'. A null can be assigned but it cannot be equated with anything, including
itself.

VARIABLES in PL/SQL

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.

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.

PL/SQL programming language allows to define various types of variables, such as


date time data types, records, collections, etc.

Variable Declaration in PL/SQL

PL/SQL variables must be declared in the declaration section or in a package as a


global variable.

When you declare a variable, PL/SQL allocates memory for the variable's value and
the storage location is identified by the variable name.

The syntax for declaring a variable is −

variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]

Where, variable_name is a valid identifier in PL/SQL, datatype must be a valid


PL/SQL data type or any user defined data type. Some valid variable declarations
along with their definition are shown below −

sales number(10, 2);


pi CONSTANT double precision := 3.1415;
name varchar2(25);
address varchar2(100);

When you provide a size, scale or precision limit with the data type, it is called
a constrained declaration. Constrained declarations require less memory than
unconstrained declarations. For example −
sales number(10, 2);
name varchar2(25);
address varchar2(100);

Initializing Variables in PL/SQL

Whenever you declare a variable, PL/SQL assigns it a default value of NULL. If you
want to initialize a variable with a value other than the NULL value, you can do so
during the declaration, using either of the following −

● The DEFAULT keyword


● The assignment operator

For example −

counter binary_integer := 0;
greetings varchar2(20) DEFAULT 'Have a Good Day';

You can also specify that a variable should not have a NULL value using the NOT
NULL constraint. If you use the NOT NULL constraint, you must explicitly assign an
initial value for that variable.

It is a good programming practice to initialize variables properly otherwise,


sometimes programs would produce unexpected results. Try the following
example which makes use of various types of variables −
Variable Scope in PL/SQL
PL/SQL allows the nesting of blocks, i.e., each program block may contain another inner block. If
a variable is declared within an inner block, it is not accessible to the outer block. However, if a
variable is declared and accessible to an outer block, it is also accessible to all nested inner blocks.
There are two types of variable scope −
● 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.

Following example shows the usage of Local and Global variables in its simple form −

Assigning SQL Query Results to PL/SQL Variables


You can use the SELECT INTO statement of SQL to assign values to PL/SQL variables. For each
item in the SELECT list, there must be a corresponding, type-compatible variable in the INTO list.
The following example illustrates the concept. Let us create a table named CUSTOMERS −
Constants and Literals:

A constant holds a value that once declared, does not change in the program. A constant
declaration specifies its name, data type, and value, and allocates storage for it. The declaration
can also impose the NOT NULL constraint.

Declaring a Constant

A constant is declared using the CONSTANT keyword. It requires an initial value and does not
allow that value to be changed. For example −
The PL/SQL Literals

A literal is an explicit numeric, character, string, or Boolean value not represented


by an identifier. For example, TRUE, 786, NULL, 'tutorialspoint' are all literals of
type Boolean, number, or string. PL/SQL, literals are case-sensitive. PL/SQL
supports the following kinds of literals −

● Numeric Literals
● Character Literals
● String Literals
● BOOLEAN Literals
● Date and Time Literals

The following table provides examples from all these categories of literal values.
PL/SQL Operators:
PL/SQL language is rich in built-in operators and provides the following types of operators −
● Arithmetic operators
● Relational operators
● Comparison operators
● Logical operators
● String operators

Arithmetic Operators

Following table shows all the arithmetic operators supported by PL/SQL. Let us assume variable
A holds 10 and variable B holds 5, then −

Operator Description Example

+ Adds two operands A + B will give 15

- Subtracts second operand from the first A - B will give 5

* Multiplies both operands A * B will give 50

/ Divides numerator by de-numerator A / B will give 2

Exponentiation operator, raises one operand to the power of A ** B will give


**
other 100000

Relational Operators

Relational operators compare two expressions or values and return a Boolean result. Following
table shows all the relational operators supported by PL/SQL. Let us assume variable A holds
10 and variable B holds 20, then −

Operator Description Example


Checks if the values of two operands are equal or not, if yes then (A = B) is not
=
condition becomes true. true.

!= Checks if the values of two operands are equal or not, if values are not (A != B) is
<> equal then condition becomes true. true.
~=

Checks if the value of left operand is greater than the value of right (A > B) is not
>
operand, if yes then condition becomes true. true.

Checks if the value of left operand is less than the value of right
< (A < B) is true.
operand, if yes then condition becomes true.

Checks if the value of left operand is greater than or equal to the value (A >= B) is not
>=
of right operand, if yes then condition becomes true. true.

Checks if the value of left operand is less than or equal to the value of (A <= B) is
<=
right operand, if yes then condition becomes true. true

Comparison Operators

Comparison operators are used for comparing one expression to another. The result is always
either TRUE, FALSE or NULL.

Operator Description Example

The LIKE operator compares a character, string,


If 'Zara Ali' like 'Z% A_i' returns a
or CLOB value to a pattern and returns TRUE if
LIKE Boolean true, whereas, 'Nuha Ali'
the value matches the pattern and FALSE if it
like 'Z% A_i' returns a Boolean false.
does not.

If x = 10 then, x between 5 and 20


The BETWEEN operator tests whether a value
returns true, x between 5 and 10
BETWEEN lies in a specified range. x BETWEEN a AND b
returns true, but x between 11 and
means that x >= a and x <= b.
20 returns false.

If x = 'm' then, x in ('a', 'b', 'c')


The IN operator tests set membership. x IN (set)
IN returns Boolean false but x in ('m',
means that x is equal to any member of set.
'n', 'o') returns Boolean true.

The IS NULL operator returns the BOOLEAN value


TRUE if its operand is NULL or FALSE if it is not If x = 'm', then 'x is null' returns
IS NULL
NULL. Comparisons involving NULL values always Boolean false.
yield NULL.
Logical Operators

Following table shows the Logical operators supported by PL/SQL. All these operators work on
Boolean operands and produce Boolean results. Let us assume variable A holds true
and variable B holds false, then −

Operator Description Examples

Called the logical AND operator. If both the operands are true then (A and B) is
and
condition becomes true. false.

Called the logical OR Operator. If any of the two operands is true then (A or B) is
or
condition becomes true. true.

Called the logical NOT Operator. Used to reverse the logical state of its
not (A and B)
not operand. If a condition is true then Logical NOT operator will make it
is true.
false.

PL/SQL Operator Precedence

Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
The precedence of operators goes as follows: =, <, >, <=, >=, <>, !=, ~=, ^=, IS NULL, LIKE,
BETWEEN, IN.

Operator Operation

** exponentiation

+, - identity, negation

*, / multiplication, division

+, -, || addition, subtraction, concatenation

comparison
NOT logical negation

AND conjunction

PL/SQL Conditional Statements:


Decision-making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Following is the general form of a typical conditional (i.e., decision making) structure found in
most of the programming languages −

PL/SQL programming language provides following types of decision-making statements.

[Link] Statement & Description

IF - THEN statement
1 The IF statement associates a condition with a sequence of statements enclosed by the
keywords THEN and END IF. If the condition is true, the statements get executed and if
the condition is false or NULL then the IF statement does nothing.

IF-THEN-ELSE statement
2 IF statement adds the keyword ELSE followed by an alternative sequence of statement.
If the condition is false or NULL, then only the alternative sequence of statements get
executed. It ensures that either of the sequence of statements is executed.

IF-THEN-ELSIF statement
3
It allows you to choose between several alternatives.

Case statement

Like the IF statement, the CASE statement selects one sequence of statements to
4 execute.
However, to select the sequence, the CASE statement uses a selector rather than
multiple Boolean expressions. A selector is an expression whose value is used to select
one of several alternatives.

5 Searched CASE statement


The searched CASE statement has no selector, and it's WHEN clauses contain search
conditions that yield Boolean values.

nested IF-THEN-ELSE
6
You can use one IF-THEN or IF-THEN-ELSIF statement inside another IF-THEN or IF-
THEN-ELSIF statement(s).
IF statement:

It is the simplest form of the IF control statement, frequently used in decision-making and
changing the control flow of the program execution.

The IF statement associates a condition with a sequence of statements enclosed by the


keywords THEN and END IF. If the condition is TRUE, the statements get executed, and if the
condition is FALSE or NULL, then the IF statement does nothing.

Syntax

Syntax for IF-THEN statement is −

IF condition THEN
S;
END IF;

Flow Diagram
If-Then-Else:
Flow Diagram

Example:
If-then-Elsif :
CASE statement;
Nested – if:
Loops:

There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated
execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −
Basic Loop:
Basic loop structure encloses sequence of statements in between the LOOP and END
LOOP statements. With each iteration, the sequence of statements is executed and then control
resumes at the top of the loop.

Syntax
The syntax of a basic loop in PL/SQL programming language is −
LOOP
Sequence of statements;
END LOOP;

Here, the sequence of statement(s) may be a single statement or a block of statements. An EXIT
statement or an EXIT WHEN statement is required to break the loop.

While Loop:
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;

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;

Following is the flow of control in a For Loop −

● The initial step is executed first, and only once. This step allows you to declare and initialize any
loop control variables.
● Next, the condition, i.e., initial_value .. final_value is evaluated. If it is TRUE, the body of the loop
is executed. If it is FALSE, the body of the loop does not execute and the flow of control jumps to
the next statement just after the for loop.
● After the body of the for loop executes, the value of the counter variable is increased or
decreased.
● The condition is now evaluated again. If it is TRUE, the loop executes and the process repeats
itself (body of loop, then increment step, and then again condition). After the condition becomes
FALSE, the FOR-LOOP terminates.
Following are some special characteristics of PL/SQL for loop −
● The initial_value and final_value of the loop variable or counter can be literals, variables, or
expressions but must evaluate to numbers. Otherwise, PL/SQL raises the predefined exception
VALUE_ERROR.
● The initial_value need not be 1; however, the loop counter increment (or decrement) must be
1.
● PL/SQL allows the determination of the loop range dynamically at run time.

Nested Loops:

PL/SQL allows using one loop inside another loop. Following section shows a few examples to
illustrate the concept.

The syntax for a nested basic LOOP statement in PL/SQL is as follows −

LOOP
Sequence of statements1
LOOP
Sequence of statements2
END LOOP;
END LOOP;

The syntax for a nested FOR LOOP statement in PL/SQL is as follows −

FOR counter1 IN initial_value1 .. final_value1 LOOP


sequence_of_statements1
FOR counter2 IN initial_value2 .. final_value2 LOOP
sequence_of_statements2
END LOOP;
END LOOP;

The syntax for a nested WHILE LOOP statement in Pascal is as follows −

WHILE condition1 LOOP


sequence_of_statements1
WHILE condition2 LOOP
sequence_of_statements2
END LOOP;
END LOOP;

Cursors in Pl/SQL
Oracle creates a memory area, known as the context area, for processing an SQL statement,
which contains all the information needed for processing the statement; for example, the
number of rows processed, etc.

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.

zbThe following table provides the description of the most used attributes −

[Link] Attribute & Description

%FOUND
1 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
2 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
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.

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 we had created and used in the previous chapters.
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 |
+----+----------+-----+-----------+----------+
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 [Link]%type;
c_name [Link]%type;
c_addr [Link]%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
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.

You might also like