RDBMS Unit-4
RDBMS Unit-4
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
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
Faculty of : FCE. Program: BTech Class/Section: 4 F / J Date: ……………………….
Name of Faculty: Dr. S.K.Kapoor Name of Course: RDBMS Code: BCECCE4103
Nature of It is an application-oriented
4. It is a Data-oriented language.
Orientation language.
Declarative/
PL/SQL is a procedural
6. Procedural SQL is a declarative language.
language.
Language
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.
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
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
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.
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.
# 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 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
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
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.
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;
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
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;
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;
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;
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.
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
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;
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
23