Rdbms Unit-III PL-SQL
Rdbms Unit-III PL-SQL
INTRODUCTION TO PL/SQL:
SQL PL/SQL
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:
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';
(***) 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.
Output:
Hello World
PL/SQL procedure successfully completed.
PL/SQL Identifiers
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 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.
Scalar
1 Single values with no internal components, such as a NUMBER,
DATE, or BOOLEAN.
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.
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.
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)
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)
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
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 predefines several subtypes in package STANDARD. For example, PL/SQL predefines the
subtypes CHARACTER and INTEGER as follows −
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.
By default, variable names are not case-sensitive. You cannot use a reserved
PL/SQL keyword as a variable name.
When you declare a variable, PL/SQL allocates memory for the variable's value and
the storage location is identified by the variable name.
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);
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 −
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.
Following example shows the usage of Local and Global variables in its simple form −
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
● 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 −
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 −
!= 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.
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 −
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.
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
comparison
NOT logical negation
AND conjunction
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.
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.
Syntax
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;
● 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.
LOOP
Sequence of statements1
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.
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.
zbThe following table provides the description of the most used attributes −
%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
+----+----------+-----+-----------+----------+
| 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.
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 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 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 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