0% found this document useful (0 votes)
12 views49 pages

Unit-4 Dbmsupdated

The document introduces PL/SQL as a procedural extension of SQL, addressing SQL's limitations in procedural capabilities, error handling, and performance in multi-user environments. It outlines the advantages of PL/SQL, including support for conditional logic, improved performance through batch processing, and user-friendly error messages. Additionally, it describes the structure of PL/SQL blocks, control structures, and transaction management, emphasizing the importance of COMMIT, ROLLBACK, and SAVEPOINT in managing database transactions.

Uploaded by

prajwalprabhu025
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)
12 views49 pages

Unit-4 Dbmsupdated

The document introduces PL/SQL as a procedural extension of SQL, addressing SQL's limitations in procedural capabilities, error handling, and performance in multi-user environments. It outlines the advantages of PL/SQL, including support for conditional logic, improved performance through batch processing, and user-friendly error messages. Additionally, it describes the structure of PL/SQL blocks, control structures, and transaction management, emphasizing the importance of COMMIT, ROLLBACK, and SAVEPOINT in managing database transactions.

Uploaded by

prajwalprabhu025
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
You are on page 1/ 49

Unit 4 DBMS II BCA

INTRODUCTION TO PL/SQL
Though SQL is the natural language of the DBA, it
suffers from various inherent disadvantages, when used as
a conventional programming language.
1. SQL does not have any procedural capabilities i.e.
SQL does not provide the programming techniques of
condition checking, looping and branching that is vital
for data testing before its permanent storage.
2. SQL statements are passed to the Oracle Engine one
at a time. Each time an SQL statement is executed, a
call is made to the engine's resources. This adds to the
traffic on the network, thereby decreasing the speed of
data processing, especially in a multi-user
environment.
3. While processing an SQL sentence if an error occurs,
the Oracle engine displays its own error messages.
SQL has no facility for programmed handling of errors
that arise during the manipulation of data.
As the name suggests, PL/SQL is a superset of SQL.
PL/SQL is a block-structured language that enables
developers to combine the power of SQL with procedural
statements. PL/SQL bridges the gap between database
technology and procedural programming languages.
ADVANTAGES OF PL/SQL:
1. PL/SQL is development tool that not only supports
SQL data manipulation but also provides facilities of
conditional checking, branching and looping.
2. PL/SQL sends an entire block of SQL statements to
the Oracle engine all in one go. Communication
between the program block and the Oracle engine
reduces considerably, reducing network traffic. Since
the Oracle engine got the SQL statements as a single
block, it processes this code much faster than if it got
the code one sentence at a time. There is a definite
improvement in the performance time of the Oracle
engine. As an entire block of SQL code is passed to the
Oracle engine at one time for execution, all changes
made to the data in the table are done or undone, in
one go.
3. PL/SQL also permits dealing with errors as required,
and facilitates displaying user-friendly messages, when
errors are encountered.

1
Unit 4 DBMS II BCA

4. PL/SQL allows declaration and use of variables in


blocks of code. These variables can be used to store
intermediate results of a query for later processing, or
calculate values and insert them into an Oracle table
later. PL/SQL variables can be used anywhere, either
in SQL statements or in PL/SQL blocks.
5. Via PL/SQL, all sorts of calculations can be done
quickly and efficiently without the use of the Oracle
engine. This considerably improves transaction
performance.
6. Applications written in PL/SQL are portable to any
computer hardware and operating system, where
Oracle is operational. Hence, PL/SQL code blocks
written for a DOS version of Oracle will run on its
Linux / UNIX version, without any modifications at
all.

THE GENERIC PUSQL BLOCK


A PL/SQL block has a definite structure, which can be
divided into sections. The sections of a PL/SQL block are:
 The Declare section
 The Master Begin and End section
 Optionally containsan Exception section.

A PL/SQL code block can be diagrammatically


represented as follows:

Each of these is explained below:

2
Unit 4 DBMS II BCA

The Declare Section:


Code blocks start with a declaration section, in which,
memory variables and other Oracle objects can be declared,
and if required initialized. Once declared, they can be used
in SQL statements for data manipulation.

The Begin Section:


It consists of a set of SQL andPL/SQL statements,
which describe processes that have to be applied to table
data. Actual data manipulation, retrieval, looping and
branching constructs are specified in this section.

Exception Section:
This section deals with handling of errors that arise
during execution of the data manipulation statements,
which make up the PL/SQL code block. Errors can arise
due to syntax, logic and/or validation rule violation.

The End Section:


This marks the end of a PL/SQL block.

THE PL/SQL EXECUTION ENVIRONMENT


Wherever PL/SQL technology is required, the PL/SQL
engine accepts any valid PL/SQL block as input.
These blocks are sent to the PL/SQL engine, where
procedural statements are executed and SQL statements are
sent to the SQL executor in the Oracle engine. Since the
PL/SQL engine resides in the Oracle engine, this is an
efficient and swift operation. The call to the Oracle engine
needs to be made only once to execute any number of SQL
statements, if these SQL sentences are bundled inside a
PL/SQL block.
Diagram 15.2 gives an idea of how these statements
are executed and how convenient it is to bundle SQL code
within a PL/SQL block.

3
Unit 4 DBMS II BCA

PLlSQL
The Character Set:
The basic character set includes the following:

Literals:
A literal is a numeric value or a character string used
to represent itself.
 Numeric Literal:
These can be either integers or floats. If a float is being
represented, then the integer part must be separated from
the float part by a period.

 String Literal:
These are represented by one or more legal characters
and must be enclosed within single quotes. The single quote
character can be represented, by writing it twice in a string
literal. This is definitely not the same as a double quote.

 Character Literal:
These are string literals consisting of single characters.

4
Unit 4 DBMS II BCA

 Logical (Boolean) Literal:


These are predetermined constants. The values that can
be assigned to this data type are: TRUE, FALSE, NULL.

PL/SQL Data Types


Both PL/SQL and Oracle have their foundations in
SQL. Most PL/SQL data types are native to Oracle's data
dictionary. Hence, there is a very easy integration of PL/SQL
code with the Oracle Engine.
The default data types that can be declared in PL/SQL are
number (for storing numeric data), char (for storing
character data), date (for storing date and time data),
boolean (for storing TRUE, FALSE or NULL). number, char
and date data types can have NULL values.
The %TYPE attribute provides for further integration.
PL/SQL can use the %TYPE attribute to declare variables
based on definitions of columns in a table. Hence, if a
column's attributes change, the variable's attributes will
change as well. This provides for data independence,
reduces maintenance costs, and allows programs to adapt
to changes made to the table.
% TYPE declares a variable or constant to have the
same data type as that of a previously defined variable or of
a column in a table or in a view. When referencing a table, a
user may name the table and the column, or name the
owner, the table and the column.
NOT NULL causes creation of a variable or a constant
that cannot be assigned a null value. If an attempt is made
to assign the value NULL to a variable or a constant that
has been assigned a NOT NULL constraint, Oracle senses
the exception condition automatically and an internal error
is returned.
Note: As soon as variable or constant has been
declared as NOT NULL, it must be assigned a value. Hence
every variable or constant declared as NOT NULL needs to
be followed by a PL/SQL expression that loads a value into
the variable constant.

Variables: Variables in PL/SQL blocks are named


variables. A variable name must begin with a character and
can be followed by a maximum of 29 other characters.

5
Unit 4 DBMS II BCA

Reserved words cannot be used as variable names


unless enclosed within double quotes. Variables must be
separated from each other by at least one space or by a
punctuation mark.
Case is insignificant when declaring variable names. A
space cannot be used in a variable name. A variable of any
data type either native to oracle Engine such as number,
char, date and so on or native to PL/SQL such as Boolean
(i.e. logical variable content) can be declared.

Logical Comparisons:
PL/SQL supports the comparison between variables
and constants in SQL and PL/SQL statements. These
comparisons, often called Boolean expressions, generally
consist of simple expressions separated by relational
operators (<, >, =, <>, >=, <=) that can be connected by
logical operators (AND, OR, NOT). A Boolean expression will
always evaluate to TRUE, FALSE or NULL.

Displaying User Messages on the VDU Screen:


Programming tools require a method through which
messages can be displayed on the VOU screen.
 DBMS_OUTPUT is a package that includes a number
of procedures and functions that accumulate
information in a buffer so that it can be retrieved later.
These functions can also be used to display messages.
 PUT_LINE puts a piece of information in the package
buffer followed by an end-of-line marker. It can also be
used to display a message. PUT_LINE expects a single
parameter of character data type. If used to display a
message, it is the message string.
To display messages, the SERVEROUTPUT should be set
to ON. SERVEROUTPUT is a SQL *PLUS environment
parameter that displays the information passed as a
parameter to the PUT_LINE function.
Syntax:
SET SERVEROUTPUT [ON/OFF]
Comments:
A comment can have two forms, as follows:
1. The comment line begins with a double hyphen (--).
The entire line will be treated as a comment.

6
Unit 4 DBMS II BCA

2. The comment line begins with a slash followed by an


asterisk (/*) till the occurrence of an asterisk followed
by a slash (*/). All lines within are treated as
comments. This form of specifying comments can be
used to span across multiple lines.

CONTROL STRUCTURE:
The flow of control statements can be classified into the
following categories:
 Conditional Control
 Iterative Control
 Sequential Control

Conditional Control:
PL/SQL allows the use of an IF statement to control the
execution of a block of code. In PL/SQL, the IF - THEN -
ELSIF - ELSE - END IF construct in code blocks allow
specifying certain conditions under which a specific block of
code should be executed.

Example:
PL\SQL program to check the given number is odd or
even.
declare
num number(2);
begin
num:=&EnterNumber;
if num mod 2 =0 then
dbms_output.put_line(‘ Given number is even’);
else
dbms_output.put_line(‘Given number is odd’);
end if;
end;

7
Unit 4 DBMS II BCA

output:
SQL>/
EnterNumber:4
Given number is even
Procedure successfully complted.

Iterative Control:
Iterative control indicates the ability to repeat or skip
sections of a code block. A loop marks a sequence of
statements that has to be repeated. The keyword loop has to
be placed before the first statement in the sequence of
statements to be repeated, while the keyword end loop is
placed immediately after the last statement in the sequence.
Once a loop begins to execute, it will go on forever. Hence a
conditional statement that controls the number of times a
loop is executed always accompanies loops. PL/SQL
supports the following structures for iterative control:

Simple Loop:
In simple loop, the key word loop should be placed before
the first statement in the sequence and the keyword end
loop should be written at the end of the sequence to end the
loop.

Example: PL/SQL program to print first N natural numbers


using simple loop.
declare
i number(1):=1;
num number(2);
begin
num:=&EnterNumber;

loop
exit when i>num;
dbms_output.put_line(i);
i:=i+1;
end loop;
end;
Output:

8
Unit 4 DBMS II BCA

SQL>/
EnterNumber:5
1
2
3
4
5
Procedure successfully completed.

The WHILE loop:

Example: PL/SQL program to print first N natural numbers


using while loop.
declare
i number(1):=1;
num number(2);
begin
num:=&EnterNumber;
while i<=num
loop
dbms_output.put_line(i);
i:=i+1;
end loop;
end;
Output:
SQL>/
EnterNumber:5
1
2
3
4
5

9
Unit 4 DBMS II BCA

The FOR Loop:

Example1:
PL/SQL program to display the first N natural numbers
using for loop.
declare
num number(2);
i number(2);
begin
num:=&EnterNumber;
for i in 1..num
loop
dbms_output.put_line(i);
end loop;
end;
Output:
SQL>/
EnterNumber:5
1
2
3
4
5

Example2: PL/SQL program to display the first N natural


numbers in reverse order using for loop.
declare
num number(2);
i number(2);
begin
num:=&EnterNumber;
for i in reverse 1..num
loop
dbms_output.put_line(i);
end loop;
end;

10
Unit 4 DBMS II BCA

Output:
SQL>/
EnterNumber:5
5
4
3
3
1

Sequential Control
The GOTO Statement:
The GOTO statement changes the flow of control
within a PL/SQL block. This statement allows execution of a
section of code, which is not in the normal flow of control.
The entry point into such a block of code is marked using
the tags <<user-defined name>>. The GOTO statement can
then make use of this user-defined name to jump into that
block of code for execution.

Example:
Declare

PL/SQL TRANSACTIONS
ORACLE TRANSACTIONS:
A series of one or more SQL statements that are
logically related or a series of operations performed on
Oracle table data is termed as a Transaction. Oracle treats
this logical unit as a single entity. Oracle treats changes to
table data as a two-step process.
 A COMMIT statement given at the SQL prompt can be
used to make the changes permanent.
 A ROLLBACK statement given at the SQL prompt can
be used to undo a part of or the entire transaction.
A transaction is a group of events that occur between any of
the following events:
o Connecting to Oracle
o Disconnecting from Oracle
o Committing changes to the database table
o Rollback

11
Unit 4 DBMS II BCA

Closing Transactions:
A transaction can be closed by using either a commit
or a rollback statement. By using these statements, table
data can be changed or all the changes made to the table
data undone.

Using COMMIT:
A COMMIT ends the current transaction and makes
permanent any changes made during the transaction. All
transactional locks acquired on tables are released.

Using ROLLBACK:
A ROLLBACK does exactly the opposite of COMMIT. It
ends the transaction but undoes any changes made during
the transaction. All transactional locks acquired on tables
are released.

Creating A SAVEPOINT:
SAVEPOINT marks and saves the current point in the
processing of a transaction. When a SAVEPOINT is used
with a ROLLBACK statement, parts of a transaction can be
undone. An active SAVEPOINT is one that is specified since
the last COMMIT or ROLLBACK.

ROLLBACK can be fired- from the SQL prompt with or·


without the SAVEPOINT clause. The implication of each is
described below.
A ROLLBACK operation performed without the SAVEPOINT
clause amounts to the following:
 Ends the transaction
 Undoes all the changes in the current transaction
 Erases all savepoints in that transaction

12
Unit 4 DBMS II BCA

 Releases the transactional locks


Example:
Refer class Notes:

A ROLLBACK operation performed with the TO


SAVEPOINT clause amounts to the following:
 A predetermined portion of the transaction is rolled
back
 Retains the save point rolled back to, but loses those
created after the named savepoint
 Releases all transactional locks that were acquired
since the savepoint was taken

PROCESSING A PL/SQL BLOCK:


A PL/SQL block can be run in one of two modes:
 Batch processing wherein records are gathered in a
table and at regular intervals manipulated
 Real Time processing wherein records are manipulated
as they are created (in real time)

Oracle and the Processing Of SQL Statements


Whenever an SQL statement is executed, Oracle engine
performs the following tasks:
 Reserves a private SQL area in memory
 Populates this area with the data requested in the SQL
sentence
 Processes the data in this memory area as required
 Frees the memory area when the processing of data is
complete

WHAT IS A CURSOR?
The Oracle Engine uses a work area for its internal
processing in order to execute an SQL statement. This
work area is private to SQL's operations and is called a
Cursor. The data that is stored in the cursor is called the
Active Data Set. Conceptually, the size of the cursor in
memory is the size required to hold the number of rows in
the Active Data Set.

13
Unit 4 DBMS II BCA

Types of Cursors:
Cursors are classified depending on the circumstances
under which they are opened.
1. If the Oracle engine opened a cursor for its internal
processing it is known as an Implicit Cursor.
2. A cursor can also be opened for processing data
through a PL/SQL block, on demand. Such a user-
defined cursor is known as an Explicit Cursor.

General Cursor Attributes:


When the Oracle engine creates an Implicit or Explicit
cursor, cursor control variables are also created to control
the execution of the cursor. These are a set of four system
variables, which keep track of the Current status of a
cursor. These cursor variables can be accessed and used in
a PL/SQL code block.

Implicit Cursor:
The Oracle engine implicitly opens a cursor on the
Server to process each SQL statement. Since the implicit
cursor is opened and managed by the Oracle engine
internally, the function of reserving an area in memory,
populating this area with appropriate data, processing the
data in the memory area, releasing the memory area when
the processing is complete is taken care of by the Oracle
engine. The resultant data is then passed to the client
machine via the network. A cursor is then opened in
memory on the client machine to hold the rows returned by
the Oracle engine. The number of rows held in the cursor on
the client is managed by the client's operating system and
it's swap area.

14
Unit 4 DBMS II BCA

Example4:
The bank manager has decided to transfer employees across branches. Write
a PL/SQL block to accept anemployee number and the branch number
followed by updating the branch number of that employee towhich he belongs
appropriately. Display an appropriate message using SQL%FOUND based on
theexistence of the record in the EMP_MSTR table. Display an appropriate
message usingSQL%NOTFOUND based on the non-existence of the record
in the EMP_MSTR table.

BEGIN
UPDATE EMP MSTR SET BRANCH NO = &BRANCH _NO WHERE
EMP_N0&EMP NO;
IF SQL%FOUND THEN
dbms_output.put_line(Employee Successfully Transferred);
END IF;
IF SQL%NOTFOUND THEN
dbms_output.put_line('Employee Number does not Exist);
END IF;
END;
Output:
Enter value for branch no: 'B4'
old 2: UPDATE EMP_MSTR SET BRANCH_NO= &BRANCH NO
new 2: UPDATE EMP MSTR SET BRANCH NO = 'B4'
Enter value for emp no: 'E1'
old 3 WHERE EMP NO = &EMP NO;
new 3: WHERE EMP NO = 'E1';
Employee Successfully Trans ferred
PL/SQL procedure successfully completed.

15
Unit 4 DBMS II BCA

Example 5:
For SQL%ROWCOUNT
The bank manager of Darya Ganj branch decides to activate all those
accounts, which were previously
marked as inactive for performing no transactions in last 365 days. Write a
PL/sQL block to update the
status of accounts. Display an appropriate message based on the number of
rows affected by the update
fired.

DECLARRE
Rows_Affected char(4);
BĘGIN
UPDATE ACCT_MSTR SET STATUS = 'A' WHERE STATUS = 'S' AND
BRANCH NO IN(SELECT BRANCH_NO FROM BRANCH_MSTR
WHERE NAME = "Darya Ganj);
Rows_Afected To_CHAR(SQL%ROWCOUNT);
IF SQL%ROWCOUNT> 0 THEN
dbms_output-put_line(Rows Afected || Account(s) Activated
Successfully);
ELSE
dbms_output.put_line('Currently there exist no Inactive Accounts in the
Darya Ganj Branch');
END IF;
END;

Output:
2 Account (s) Activated Successfully
PL/SQL procedure successfully completed.

Explicit Cursor:
When individual records in a table have to be
processed inside it PL/SQL code block a cursor is used.
This cursor will be declared and mapped to an SQL query in
the Declare Section of the PL/SQL block and used within its
Executable Section. A cursor thus created and used is
known as an Explicit Cursor.

16
Unit 4 DBMS II BCA

Explicit Cursor Management:


The steps involved in using an explicit cursor and
manipulating data in its active set are:
o Declare a cursor mapped to a SQL select statement
that retrieves data for processing
o Open the cursor
o Fetch data from the cursor one row at a time into
memory variables
o Process the data held in the memory variables as
required using a loop
o Exit from the loop after processing is complete
o Close the cursor

Cursor Declaration:
A cursor is defined in the declarative part of a PL/SQL
block. This is done by naming the cursor and mapping it to
a query. When a cursor is declared, the Oracle engine is
informed that a cursor of the said name needs to be opened.
The declaration is only intimation. There is no memory
allocation at this point in time. The three commands used to
control the cursor subsequently are open, fetch and close.

The Functionality Of Open, Fetch And Close Commands:


 Initialization of a cursor takes place via the open
statement, this:
o Defines a private SQL area named after the
cursor name
o Executes a query associated with the cursor
o Retrieves table data and populates the named
private SQL area in memory i.e. creates the
Active Data Set
o Sets the cursor row pointer in the Active Data
Set to the first record
 A fetch statement then moves the data held in the
Active Data Set into memory variables. Data held in
the memory variables can be processed as desired. The
fetch statement is placed inside a Loop ... End Loop
construct, which causes the data to be fetched into the
memory variables and processed until all the rows in
the Active Data Set are processed. The fetch loop
then exits. The exiting of the fetch loop is user
controlled.

17
Unit 4 DBMS II BCA

 After the fetch loop exits, the cursor must be closed


with the close statement. This will release the memory
occupied by the cursor and it’s Active Data Set.
A PL/SQL block is necessary to declare a cursor and create
an Active Data Set. The cursor name is used to reference
the Active Data Set held within the cursor.

Opening a cursor executes the query and creates the


active set that contains all rows, which meet the query
search criteria. An open statement retrieves records from a
database table and places the records in the cursor. A
cursor is opened in the Server's memory.

The fetch statement retrieves the rows from the active


set opened in the Server into memory variables declared in
the PL/SQL code block on the client one row at a time. The
memory variables are opened on the client machine. Each
time a fetch is executed, the cursor pointer is advanced to
the next row in the Active Data Set. A standard loop
structure (Loop-End Loop) is used to fetch records from the
cursor into memory variables one row at a time.

The close statement disables the cursor and the active set
becomes undefined. This will release the memory occupied
by the cursor and its Data Set both on the Client and on the
Server.

18
Unit 4 DBMS II BCA

/* make the cursor changes permanent*/


COMMIT
ELSE
Dbms_output.put_line(“un able to open cursor’);
End if;
Close
END

19
Unit 4 DBMS II BCA

20
Unit 4 DBMS II BCA

21
Unit 4 DBMS II BCA

22
Unit 4 DBMS II BCA

 The sequence of statements inside the loop is executed once for every row
that is fetched, i.e. check ifany data is retrieved

 Update the STATUS field of the ACCT_MSTR table to reflect the inactivity

 Insert a record in the INACTV_ACCT_MSTR table to reflect the updation

 Automatically repeat the above steps until the data retrieval process is
complete.

 The cursor closes automatically when all the records in the cursor have been
processed. This isbecause there are no more rows left to load into
NoTrans_Rec. This situation is sensed by the FORverb which, causes the

23
Unit 4 DBMS II BCA

loop to exit.
Finally a COMMIT is fired to make the changes permanent

PARAMETERIZED CURSORS:
Commercial applications require that the query, which,
defines the cursor, be generic and the data that is retrieved
from the table be allowed to change according to need.
Oracle recognizes this and permits the creation of
parameterized cursors for use. The contents of a
parameterized cursor will constantly change depending
upon the value passed to its parameter. Since the cursor
accepts user-defined values into its parameters, thus
changing the Result set extracted, it is called as
Parameterized Cursor.
Declaring A Parameterized Cursor:

Example:
Empno Ename Dept DOJ Basic
1001 Arun Research 12-jun- 45000
1984
1002 Bhuvan Administration 01-Mar- 40000
1985
1003 Kavya Research 01-jan- 35000
1990
1004 Bharath Administration 01-jan- 35000
1990

Consider the above table employee. Create a parameterized


cursor to increment salary of each employee whenever
required.

declare
cursor e_cur(eno number) is
select basic from employee
where empno=eno;
en employee.empno%type;
bas employee.basic%type;

24
Unit 4 DBMS II BCA

begin
en:=&ENTEREMPLOYEENUMBER;
open e_cur(en);
loop
fetch e_cur into bas;
exit when e_cur%notfound;
bas:=bas+bas*0.1;
update employee
set basic=bas
where empno=en;
end loop;
close e_cur;
end;
SQL>/
ENTEREMPLOYEENUMBER:1001
Procedure successfully executed

SQL>
Select * from employee;
Empno Ename Dept DOJ Basic
1001 Arun Research 12-jun- 49500
1984
1002 Bhuvan Administration 01-Mar- 40000
1985
1003 Kavya Research 01-jan- 35000
1990
1004 Bharath Administration 01-jan- 35000
1990

PL/SQL DATABASE OBJECTS


What Are Procedures /Functions?
A Procedure or Function is a logically grouped set
of SQL and PL/SQL statements that perform a specific
task. A stored procedure or function is a named PL/SQL
code block that has been compiled and stored in one of the
Oracle engine's system tables. To make a Procedure or
Function dynamic either of them can be passed parameters
before execution. A Procedure or Function can then change
the way it works depending upon the parameters passed
prior to its execution.

25
Unit 4 DBMS II BCA

Procedures and Functions are made up of:


 A declarative part
 An executable part
 An optional exception-handling part
Declarative Part:
The declarative part may contain the declarations of
cursors, constants, variables, exceptions and subprograms.
These objects are local to the procedure or function. The
objects become invalid once the procedure or function exits.
Executable Part:
The executable part is a PL/SQL block consisting of
SQL and PL/SQL statements that assign values, control
execution and manipulate data. The action that the
procedure or function is expected to perform is coded here.
The data that is to be returned back to the calling
environment is also returned from here. The variables
declared are put to use within this block.
Exception Handling Part
This part contains code that deals with exceptions that
may be raised during the execution of code in the
executable part. An Oracle exception handler can be
redirected to the exception handling section of the
procedure or function where the procedure or function
determines the actual action that must be carried out by
Oracle's exception handler.
WHERE DO STORED PROCEDURES AND FUNCTIONS
RESIDE?
Procedures and Functions are stored in the Oracle
database. They can be invoked or called by any PL/SQL
block that appears within an application. Before a
procedure or function is stored, the Oracle engine parses
and compiles the procedure or function.
How Does The Oracle Engine Create A Stored Procedure
or Function?
The following steps are performed automatically by the
Oracle engine while creating a procedure:
 Compiles the procedure or function
 Stores the procedure or function in the database
The Oracle engine compiles the PL/SQL code block. If an
error occurs during the compilation of the procedure or
function, an invalid procedure or function gets created. The
Oracle engine displays a message after creation that the

26
Unit 4 DBMS II BCA

procedure or function was created with compilation errors.


The compilation process does not display the errors. These
errors can be viewed using the SELECT statement:
SELECT * FROM USER_ERRORS;
When a procedure or function is invoked, the
Oracle engine loads the compiled procedure or function
in a memory area called the System Global Area (SGA).
This allows the code to be executed quickly. Once loaded in
the SGA other users also access the same procedure or
function if they have been granted permission to do so.
How Does The Oracle Engine Execute Procedures or
Functions?
The Oracle engine performs the following steps to
execute a procedure or function:
 Verifies user access
 Verifies procedure or function validity
 Executes the procedure or function
The Oracle engine checks if the user who called the
procedure or function has the execute privilege for the
procedure or function. If the user is invalid, then access is
denied otherwise the Oracle engine proceeds to check
whether the called procedure or function is valid or not. The
status of a procedure or function is shown by the use of a
select statement as follows:
SELECT <ObjectName >, <ObjectType> , <Status> FROM
<UserObjects>
WHERE <ObjectType >= <' PROCEDURE'>;
Or
SELECT <Object_Name>, <Object_Type>, <Status> FROM
<User_Objects>
WHERE <Object_Type>= <'FUNCTION'>;
Only if the status is valid, will a procedure or function
be executed. Once found valid, the Oracle engine then loads
a procedure or function into memory (i.e. if it is not
currently present in memory) and executes it.
ADVANTAGES OF USING A PROCEDURE OR FUNCTION
1. Security:
Stored procedures and functions can help enforce data
security. For e.g.
by giving permission to a procedure or function that can
query a table and granting the procedure or function to

27
Unit 4 DBMS II BCA

users, permissions to manipulate the table itself need not be


granted to users.
2. Performance:
It improves database performance in the following ways:
 Amount of information sent over a network is less.
 No compilation step is required to execute the code.
 Once the procedure or function is present in the
shared pool of the SGA retrieval from disk is not
required every time different users call the
procedure or function i.e. reduction in disk I/O.
3. Memory Allocation:
The amount of memory used reduces as stored
procedures or functions have shared memory capabilities.
Only one copy of procedure needs to be loaded for execution
by multiple users. Once a copy of a procedure or function is
opened in the Oracle engine's memory, other users who
have appropriate permission may access it when required.
4. Productivity :
By writing procedures and functions redundant coding
can be avoided, increasing productivity.
5. Integrity:
A procedure or function needs to be tested only once to
guarantee that it returns an accurate result. Since
procedures and functions are stored in the Oracle engine
they become a part of the engine's resource. Hence the
responsibility of maintaining their integrity rests with the
Oracle engine.
PROCEDURES VERSUS FUNCTIONS
The differences between Procedures and Functions can
be listed as below:
 A function must return a value back to the caller. A
function can return only one value to the calling
PL/SQL code block.
 By defining multiple OUT parameters in a procedure,
multiple values can be passed to the caller. The OUT
variable being global by nature, its value is accessible
by any PL/SQL code block including the PL/SQL
block via which it was called.

28
Unit 4 DBMS II BCA

Example:

29
Unit 4 DBMS II BCA

Example:

Using A Function
Example 1:
Consider the tables TRANS_MSTR and ACCT_MSTR. Both
the tables belong to the banking system.The TRANS_ MSTR
table is used to register the deposits or withdrawals, as
performed. As a batch processthe initial opening balance
value must be written to the TRANS_MSTR table whenever
an account isopened with the bank.

Write a PL/sQL block of code that would insert a record


representing the opening balance entry in theTRANS_MSTR
table each time an account is opened. The insert in the
TRANS_MSTR table depends on ACCTNO. In case the
ACCT_NO is not present in the TRANS MSTR table i.e. there
is no entry madefor the initial deposit, then a record is
inserted in the TRANS_MSTR table representing the initial

30
Unit 4 DBMS II BCA

paymemt made while opening an account. If there is already


an entry made for the initial payment i.e. ACCT_NO
ispresent in the TRANS_MSTR table then the insertion is
skipped.

To help simplify this process (of batch insertion) a function


called f_ChkAcctNo has been created. Thefunction checks
for the existence of ACCT_NO in the table TRANS_MSTR.
The function has oneargument, which receives a value. The
function will search for a matching value in the
TRANS_MSTRtable when a value is passed to it when being
invoked.
The function will return 1 indicating that a match is found
or 0 indicating that no match is found. This value
returned by the function is used to make a decision to
insert a record or skip the insertion in the
TRANS_MSTR table.
Creating Function For Use
A stored function is created to perform the ACCT_NO check
operation. f_ChkAcctNo) is the name of thefunction which
accepts a variable ACCT_NO and returms a value to the
host environment. The valuechanges from 0 (i.e. if ACCT_NO
does not exist) to I (i.e. if ACCT_NO exísts) depending on the
recordsretrieved.

CREATE OR REPLACE FUNCTION


F_ CHKACCTNO(VACCT_NO IN VARCHAR2)
RETURN NUMBER IS
/* Variable that: hold data from the TRANS MSTR table */
dummyAcctNo VARCHAR2(10);

BEGIN
SELECT DISTINCT ACCT_NO INTO dummyAcctNo FROM
TRANS_MSTR
WHERE ACCT_NO= vACCT_NO;
/*If the SELECT Statement retrieves data, return value is
set to1*/
RETURN 1;
EXCEPTION
/*If the SELECT statement does not retrieve data, return
value 1s
to 0 */

31
Unit 4 DBMS II BCA

WHEN NO_DATA FOUND THEN RETURN 0;


END;
Output:
Function created.
This function is then called in the PL/SQL block as follows.
The return value is then checked and appropriate action is
taken.
Calling The Function F_CHKACCTNO In A PL/SQL Code Block

DECLARE

/* Cursor SCANTABLE retrieves the required data from the


table ACCT MSTR */

CURSOR SCANTABLE IS SELECT ACCT_NO, TYPE FROM


ACCT_MSTR;

/* Variables that hold data from the cursor scantable */

mACCT_NO ACCT_MSTR.ACCT_N0%type;
mTYPE ACCT_MSTR.TYPE%type;

/*Variable that stores the value returned by the


f_ChkAccctNo function i.e. 1 or 0 */

valexists NUMBER(1);

BEGIN

OPEN SCANTABLE;

LOOP

FETCH SCANTABLE INTO MACCT_NO, MTYPE;


EXIT WHEN SCANTABLE%NOTFOUND;

/* Call function F_CHKACCTNO to check if ACCT_NO is


present in TRANS MSTR table */

valexists :=F_CHKACCTNO(MACCT_NO);

32
Unit 4 DBMS II BCA

/* If ACCT_NO does not exist insert a record in the


TRANSMSTR table*/

IF valexists = 0 THEN
IF mTYPE = 'SB' THEN
INSERT INTO TRANS_MSTR (TRANS_NO, ACCT NO,
DT, TYPE, PARTICULAR, DR_CR, AMT, BALANCE)
VALUES(SELECT T||
TO_CHAR(MAX(TO_NUMBER(SUBSTR( TRANS N
2))) + 1) FROM TRANS_MSTR), mACCT NO, SYSDATE, 'C’,
‘initial’,Payment, ‘D', 500, 500);
ELSE
INSERT INTO TRANS MSTR (TRANS_NO, ACCT_NO, DT, TYPE,
PARTICULAD
ELSE AR,DR_CR, AMT, BALANCE)
VALUES(SELECT T || TO_CHAR(MAX(TO_NUMBER(SUBSTR( TRANS No
2)) + 1) FROM TRANS_MSTR), mACCT_NO, SYSDATE, 'C', InitialPayment',
‘D', 2000, 2000);
END IF;
END IF;
END LOOP;
CLOSE SCANTABLE;
COMMIT;
END;
Output:
PL/SQL procedure success fully completed.

The Functionality Of The PL/SsQL Block Of Code Will Be As Follows:


A cursor named SCANTABLE is created which is responsible to hold
the ACCT_NO and TYPE from theACCT_MSTR table. A call is made to
the function and the value held in mACCT_NO is then passed as
aparameter. The WHERE condition of the select statement within the
function gets its value from thevariable mACCT_NO and depending on
whether the value exists in the TRANS_MTR table or not, a value
of 0 or 1 is returned to the calling PL/SQL block.
If the select statement retrieves a record from the TRANS_MSTR table
(i.e. the corresponding ACCT_NOis present in the TRANS_MSTR table)
the insertion ofa new records is skipped.

If the select retrieves no record (i.e. the ACCT_NO is not present in the
TRANS_MSTR table), a newrecord is inserted into the TRANS_MSTR
table.

The above process continues till all the records in the cursor,
SCANTABLE are processed. When all therecords have been processed

33
Unit 4 DBMS II BCA

the PL/SQL block exits the loop and the all the transactions
arecompletedwith the COMMIT statement.

UsingA Procedure
Example 2:
The current example deals with the Fixed Deposit Maturity system.
The tables involved with thisprocessing are FD_DTLS, TRANS _MSTR
and ACCT_MSTR.
Whenever a fixed deposit is due for payment and if there are
instructions given to the bank for crediting thefixed deposit amount
on maturity to their account held in the bank, an entry is. passed in
theTRANS MSTR table for deposit of the fixed deposit amount as well
as the ACCT_MSTR table is updatedto reflect the increase of the
current balance. Finally the status of that fixed deposits is updated as
M i.e.Matured in the FD_DTLS table.

In order to simplify the job of insertion and updating, of three tables


(TRANS_MSTR, FD_DTLS andACCTMSTR) each time a fixed deposit is
due for payment, a procedure is created. This procedure is then
called in the PL/SQL block while checking for those fixed deposits due
for payment.

Creating Procedure For Use


Aprocedure called PROC_INSUPD is created and stored in the
database. This procedure wnen called in a block updates the current
balance in the ACCT MSTR table and the status in ther FD_dtls table
also inserts an entry to register the credit of the fixed deposit amount
in the TRANS_MSTR table.

CKEATE OR REPLACE PROCEDURE PROC INSUPDVED NO


INVARCHAR2, VACCT _NO IN
VARCHAR2, vAMT INNUMBER) IS
*Variable declarations */

mCurBal number;

BEGIN

/* Retrieving the current balance */

SELECT CURBAL INTO mCurBal FROM ACCT MSTR WHERE


ACCT_NO = vACCT_NO

* Inserting a record in the TRANS MSTR table */

INSERT INTO TRANS_MSTR (TRANS NO, ACCT_NO, DT, TYPE,


PARTICULAR, DR_CR,AMT, BALANCE)

34
Unit 4 DBMS II BCA

VALUES((SELECT 'T'||
TO_CHAR(MAX(TO_NUMBER(SUBSTR(TRANS_NO, 2)))+ 1)
FROM TRANS _MSTR), vACCT_NO, SYSDATE, 'C’,
'FixedDepositPayment', 'D', vAMT, (mCurBal + vAMT));

* Updating the CURBAL in the ACCT_MSTR table */

UPDATE ACCT_MSTR SET CURBAL = CURBAL + vAMT WHERE


ACCT_N0 = vACCT_NO;
* Updating the STATUS in the FD DTLS table *7
UPDATE FD_DTLS SET STATUS = 'M' WHERE FD_NO = vFD_N0;
END;

Output:
Procedure created.
Calling The Procedure In A PL/SQL Code Block:
DECLARE
/* Cursor CRSR_FDCHK retrieves all the records of table FD DTLS
which are active and due for payment */

CURSOR CRSR_FDCHK IS
SELECT FD_NO, PAYTO_ACCTNO, DUEAMT FROM FD_DTLS
WHERETO_CHAR(DUEDT,DD-MM-YY') = TO_CHAR(SYSDATE,
'DD-MM-YY)AND STATUS = 'A' AND PAYTO_ACCTNO IS NOT NULL;

/* Declaration of memory variables that will hold values */

mFD_NO VARCHAR2(10);
mPAYTO_ACCTNO VARCHAR2(10);
mAMT NUMBER(8,2);
mState NUMBER := 0;

BEGIN
/* Opening the cursor */

OPEN CRSR_FDCHK;
LOOP
FETCH CRSR_FDCHK INTO mFD_NO, mPAYTO_ACCTNO, MAMT;

EXIT WHEN CRSR_FDCHK%NOTFOUND;


/* Cal1 procedure proc_insUpa to pertorm insert/update operatin ions
on tables. */

proc_insupd(mFD_NO, mP'AYTO_ACCTNO, mAMT);

/*Updating the state to i 1.e. there are fds due for payment */

mState: =1;

35
Unit 4 DBMS II BCA

END LOOP;
/ Display a message lr no FDS are due for pa yment based on the mState
variable */

IF mState = 0 THEN
DBMS_OUTPUT.PUT_LINE(‘Currently there are no fixed deposits due for
payment: );
END IF;
CLOSE CRSR_FDCHK;
COMMIT;

Output:
Currently there are no fixed deposits due for payment.
PL/SQL procedure successfully completed.

The Functionality Of The PL/SQL Block Of Code Will Be As Follows:


The above PL/SQL when fired will open a cursor called CRSR_FDCHK that will
fetch the fixed deposit number, account number to which the fixed deposit
amount will be credited and the fixed deposit due amount from the FD_DTLS
table. The cursor will fetch only those records where the fixed deposits are
active, due for payment and the account number to which the amount has to
be credited is available.

Only when such records are fetched an insert/update operation on tables


ACCT_MSTR, TRANS_MSTR AND FD_DTLS is performed via a procedure
named PROC_INSUPD. This procedure takes three arguments i.e. fixed
deposit number, account number that will be credited and the due amount.

 On the basis of these three arguments:


An insert is fired on the TRANS_MSTR table to register the maturity of the
fixed deposit

 The current balance of the specified account number is increased in the


ACCT_MSTR table

 The status of the fixed deposit is set to M i.e. the fixed deposit is now matured
In case no records are fetched by the cursor CRSR_FDCHK a message stating
"Currently there are no fixed deposits due for payment"

FINALLY A COMMIT IS FIRED TO REGISTER THE CHANGES.

DELETING A STORED PROCEDURE OR FUNCTION


A procedure or function can be deleted by using the following syntax
Syntax:

36
Unit 4 DBMS II BCA

DROP PROCEDURE<ProcedureName>;

Example 3:
DROP PROCEDURE PROC_INSUPD;
Output:
Ptocedure dropped.
Syntax:
DROP FUNCTION «FunctionName
Example 4:
DROP FUNCTION F_CHKACCTNO;
Output:
Function dropped.

ORACLE PACKAGES

A package is an Oracle object, which holds other objects within it. Objects
commonly held within apackage are procedures, functions, variables,
constants, cursors and exceptions. The tool used to create apackage is SQL*
Plus. It is a way of creating generic, encapsulated, re-useable code.

A package once written and debugged is compiled and stored in Oracle's


system tables held in an OracleDatabase. All users who have execute
permissions on the Oracle Database can then use the package.

Packages can contain PUSQĽ blocks of code, which have been written to
perform some přocess entirely on their own. These PL/ SQL blocks of code do
not require any kind of input from other PLSQL blocks ofcode. These are the
package's standalone subprograms.

Alternatively, a package can contain a subprogram that requires input from


another PLUSQL block toperform its programmed processes successfully.
These are also subprograms of the package but thesesubprograms are not
standalone.

Subprograms held within a package can be called from other stored programs,
like triggers, precompilers,or any other Interactive Oracle program like SQL*
Plus.

Note
Unlike the stored programs, the package itself cannot be called, passed
parameters to, or nested.

Components Of An Oracle Package


A package has usually two components, a specificatlon and a body. A
package's specification declares thetypes (variables of the Record type),
memory variables, constants, exceptions, cursors, and subprograms
that are available for use.

A package's body fully defines cursors, functions, and procedures and thus

37
Unit 4 DBMS II BCA

implements the specification.

Why Use Packages?


Packages offer the following advantages:
1 Packages enable the organization of commercial applications into efficient
modules. Each package iseasily understood and the interfaces between
packages are simple, clear and well defined
2. Packages allow granting of privileges efficiently
3. A package's public variables and cursors persist for the duration of the
session. Therefore all cursors
and procedures that execute in this environment can share them
Packages enable the overloading of procedures and functions when required
4 Packages improve performance by loading multiple objects into memory at
once. Therefore subsequent calls to related subprograms in the package
require no I/O
6. Packages promote code reuse through the use of libraries that contain
stored procedures and functionsthereby reducing redundant coding.

Package Specification
The package specification contains:
1.Name of the package
2.Names of the data types of any arguments
3.This declaration is local to the database and global to the package

This means that procedures, functions, variables, constants, cursors and


exceptions and other objects declared in a package are accessible from
anywhere in the package. Therefore, all the information a package needs, to
execute a stored subprogram, is contained in the package specifications itself.

Example 5:
The following is an example of package creation specification. In this example,
the specification declares a function and a procedure:

CREATE PACKAGE BNK_PCK_SPEC IS


FUNCTION F_CHKACCTNO(VACCT_NO IN VARCHAR2) RETURN NUMBER;
PROCEDURE PROC_INSUPD(VFD_ NO IN VARCHAR2, VACCT_NO IN
VARCHAR2, VAMT IN NUMBER);
END BNK_PCK_SPEC;
Output:
Package created.

Example 6:
Sometimes a specification only declares variables, constants, and exceptions,
and therefore a package body is not necessary. The following example is a
package specification for a package that does not have a package body:

38
Unit 4 DBMS II BCA

CREATE PACKAGE COSTINGS IS


TYPE REC IS RECORD(PART NAME VARCHAR2(30), PART_PRICE NUMBER,
PRICE NUMBER;. PART_OST NUMBER);
QTY NUMBER;
NO COST EXCEPTION;
COST_OR EXCEPTION;
END COSTINGS;
Output:
Package created.

39
Unit 4 DBMS II BCA

40
Unit 4 DBMS II BCA

41
Unit 4 DBMS II BCA

42
Unit 4 DBMS II BCA

43
Unit 4 DBMS II BCA

ERROR HANDLING IN PLISQL


Every PL/SQL block of code encountered by the Oracle engine is accepted as
a client. Hence the Oracle engine will make an attempt to execute every SQL
sentence within the PL/SQL block. However while executing the SQL
sentences anything can go wrong and the SQL sentence can fail.

When an sQL sentence fails the Oracle engine is the first to


recognize this as an Exception condition. ThE Oracle engine
immediately tries to handle the exception condition and
resolve it. This is done by raising abuilt-in Exception

44
Unit 4 DBMS II BCA

Handler.
An Exception Handler is nothing but a code block in
memory that will attempt to resolve the current
exception condition. The Oracle engine can recognize every
exception conditi that occurs in memory. To
handle very common and repetitive exception conditions the
Oracle engine uses Named Exception
Handlers. The Oracle engine has about fifteen to twenty
named exception handlers. In addition to this the
Oracle engine uses more than twenty thousand numbered
exception handlers. These exception handles
are identified not by names but by four integers preceded by
a hyphen (i.e. -1414). These exception handler
names are actually a set of negative signed integers. Each
Exception Handler, irrespective of how it is
identified, (i.e. by Name or Number) has code attached that
will attempt to resolve an exception condition.
This is how Oracle's, Default Exception-Handling strategy
works.
Oracle's default exception handling code can be overridden.
When this is done Oracle's default exception
handling code is not executed but the code block that takes
care of the exception condition, in the exception
section, of the PL/ SQL block is executed. This is an
example of a programmer giving explicit exception
handling instructions to an Oracle exception handler.
This means that the Oracle engine's Exception Handler
must establish whether to execute its own exception
handling code or whether it has to execute user-defined
exception handling code.
As soon as the Oracle engine invokes an exception handler
the exception handler goes back to the PL/ SQL
block from which the exception condition was raised. The
exception handler scans the PL/ SQL block for
the existence of an Exception section within the PL/ SQL
block. If an exception section within the PL
SQL block exists the exception handler scans the first word,
after the action word When, within this
exception section.
If the first word after the action word When, is the exception
handler's name then the exception handler
executes the code contained in the Then section of the

45
Unit 4 DBMS II BCA

construct as follows:
EXCEPTION
WHEN<<ExceptionName>THEN
<<User Defined Action To Be Carried OuT>>

The first word that follows the action word When must be a
String. Hence this technique will work well forthe fifteen to
twenty named exception handlers. In addition to these the
Oracle engine has twenty
thousand, numbered exception handlers, which are raised
automatically and appropriately when the Oracleengine
recognizes exception condition. User defined exception
handling code must be permitted even forthese (numbered)
exception handlers.

ORACLE'S NAMED EXCEPTION HANDLERS


The Oracle engine has a set of pre-defined Oracle error
handlers called named Exceptions. These error handlers
are referenced by their name. The following are some of the
pre-defined Oracle named exception handlers.

Example:
PL/SQL Program using the named exception
NO_DATA_FOUND
Practical list Part B 5tH Program.
USER-Named Exception Handlers:
The technique that is used is to bind a numbered
exception handler to a name using Pragma

46
Unit 4 DBMS II BCA

Exception_init(). This binding of a numbered exception


handler, to a name (i.e. a String), is done in the declare
section of a PL/SQL block.
All objects declared in the Declare section of a PLlSQL
block are not created until actually required within the
PL/SQL block. However, the binding of a numbered
exception handler to a name must be done exactly when
declared not when the exception handler is invoked due
to an exception condition.
The Pragma action word is a call to a pre-compiler,
which immediately binds the numbered exception handler
to a name when encountered.
The function Exception_init() takes two parameters:
 First is the user defined exception name
 The second is the Oracle engine's exception number.
These lines will be included in the Declare section of the
PL/SQL block.

Using this technique it is possible to bind appropriate


numbered exception handlers to names and use these
names in the Exception section of a PL/SQL block. When
this is done the default exception handling code of the
exception handler is overridden and the user-defined
exception handling code is executed.

Example:
User Defined Exception Handling (For Business Rule
Validations)

47
Unit 4 DBMS II BCA

In commercial applications data being manipulated


needs to be validated against business rules. If the data
violates a business rule, the entire record must be rejected.
In such cases, the insert SQL DML actually runs
successfully. It is the data values that the insert statement
is placing in the table, which violates the business rule.
Since the SQL DML did not cause any system error, the
Oracle engine cannot object to the erroneous data value
being inserted into a table. To trap business rules· being
violated the technique of raising user-defined exceptions
and then handling them, is used.
User-defined error conditions must be declared in the
declarative part of any PL/SQL block. In the executable
part, a check for the condition that needs special attention
is made. If that condition exists, the call to the user-defined
exception is made using a RAISE statement. The exception
once raised is then handled in the Exception handling
section of the PL/SQL code block.

Example:
Write a PL/SQL program to make a bank transaction.
Update the bank table, whenever a withdrawal operation
carried out. Display an error massage when no sufficient
balance for withdrawal. The bank table consists of following
fields: acno, name, atype, bal. Assume that account number
A0001 initially had balance amount 650.
declare
except1 exception;
ano varchar2(6);
amt number(5);
begin
ano:=’&ACCOUNTNUMBER’;
amt:=&AMOUNT;

48
Unit 4 DBMS II BCA

select bal into b from bank


where acno=ano;
if b-amt<100 then
raise except1;
else
update bank
set bal=bal-amt
where acno=ano;
end if;
exception
when except1 then
dbms_output.put_line(‘NO SUFFICIENT
BALANCE’);
end;
SQL>/
ACCOUNTNUMBER: A0001
AMOUNT: 600
NO SUFFICIENT BALANCE

49

You might also like