0% found this document useful (0 votes)
44 views

Unit 5 Using PL SQL Package

Uploaded by

Rakesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Unit 5 Using PL SQL Package

Uploaded by

Rakesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Unit 5 Using PL/SQL Packages

5.1 Introduction to PL/SQL Packages


Packages are stored libraries in the database which allow us to group related PL/SQL
objects under one name. Or in simple words, Packages are logical groups of related
PL/SQL objects. Packages are named PL/SQL Blocks which mean they are
permanently stored into the database schema and can be referenced or reused by
your program.
In PL/SQL, a package is a schema object that contains definitions for a group of
related functionalities. A package includes variables, constants, cursors, exceptions,
procedures, functions, and subprograms.
Typically, a package has a specification and a body. A package specification is
mandatory while the package body can be required or optional, depending on the
package specification.
The following picture illustrates PL/SQL packages:

What are the contents included in a package?

A package can hold multiple database objects such as

• Stored Procedures
• PL/SQL Functions
• Database Cursors
• Type declarations as well as
• Variables
Package Architecture

PL/SQL package is divided into two parts:

1. The Package Specification, also known as the Header and


2. The Package Body
Both these parts are stored separately in the data dictionary. The package
specification is the required part whereas the package body is optional, but it is a
good practice to provide the body to the package.

5.2 Advantages of PL/SQL Packages


The package is a powerful feature of PL/SQL that you should use it in any project.
The following are the advantages of the package:

Make code more modular


Packages allow you to encapsulate logically related types, variables, constants,
subprograms, cursors, and exceptions in named PL/SQL modules. By doing this,
you make each package more reusable, manageable, readable and reliable.

Hide implementation details


Packages allow you to expose the functionality via their specifications and hide the
detailed implementation in the package body.

It means that you can enhance the code in the body of the package without affecting
other dependent packages or applications.

Improve application performance


Oracle loads the package into memory at the first time you invoke a package
subprogram. The subsequent calls of other subprograms in the same package do not
require disk I/O. This mechanism helps improve performance.

Minimize unnecessary recompiling code


Packages help avoid the unnecessary recompiling process. For instance, if you
change the body of a package function, Oracle does not recompile the subprograms
that use the function, because the subprograms are only dependent on the package
specification, not the package body.
5.3 The Package Specification
Package specification is also known as the package header. It is the section where
we put the declaration of all the package elements. Whatever elements we declare
here in this section are publicly available and can be referenced outside of the
package.

Below are few characteristics of the Package specification.

• The elements which are all declared in the specification can be accessed from
outside of the package. Such elements are known as a public element.
• The package specification is a standalone element that means it can exist alone
without package body.
• Whenever a package has referred an instance of the package is created for that
particular session.
• After the instance is created for a session, all the package elements that are
initiated in that instance are valid until the end of the session.

Syntax
CREATE [OR REPLACE] PACKAGE <package_name>
IS
<sub_program and public element declaration>
.
.
END <package name>

5.4 Package Body


In package body we provide the actual structure to all the package elements which
we have already declared in the specification by programming them. Or we can say
that a package body contains the implementation of the elements listed in the
package specification.
Unlike package specification a package body can contain both declaration of the
variable as well as the definition of all the package elements. Any package elements
such as PL/SQL Function, a cursor or a stored procedure which is not in the package
specification but coded in the package body is called Private Package Elements and
thus they cannot be referenced outside the package.
Below are characteristics of a package body.

• It should contain definitions for all the subprograms/cursors that have been
declared in the specification.
• It can also have more subprograms or other elements that are not declared in
specification. These are called private elements.
• It is a dependable object, and it depends on package specification.
• The state of the package body becomes 'Invalid' whenever the specification is
compiled. Therefore, it needs to be recompiled each time after the compilation
of specification.
• The private elements should be defined first before they are used in the
package body.
• The first part of the package is the global declaration part. This includes
variables, cursors and private elements (forward declaration) that is visible to
the entire package.
• The last part of the package is Package initialization part that executes one
time whenever a package is referred first time in the session.

Syntax
CREATE [OR REPLACE] PACKAGE BODY <package_name>
IS
<global_declaration part>
<Private element definition>
<sub_program and public element definition>
.
<Package Initialization>
END <package_name>

Referring Package Elements

Once the elements are declared and defined in the package, we need to refer the
elements to use them.

All the public elements of the package can be referred by calling the package name
followed by the element name separated by period

i.e. '<package_name>.<element_name>'.
The public variable of the package can also be used in the same way to assign and
fetch values from them

i.e. '<package_name>.<variable_name>'.

How to Create Package?

As we talked while discussing the architecture of the package in the previous topic
that the package is divided into two parts, which are

• Package header and


• The package body

Example: In this example, we are going to create a package to get and set the values
of employee's information in 'emp' table. The get_record function will return the
record type output for the given employee number, and set_record procedure will
insert the record type record into the emp table.

Step 1) Package Specification Creation

CREATE OR REPLACE PACKAGE pkg_get_set


IS
PROCEDURE set_record (p_emp_rec IN emp%ROWTYPE);
FUNCTION get record (p_emp no IN NUMBER) RETURN emp%ROWTYPE;
END pkg_get_set:
/

Output:

Package created

Step 2) Package contains Package body, where all procedures and functions actual
definition will be defined. In this step, Package Body is created.

CREATE OR REPLACE PACKAGE BODY pkg_get_set


IS
PROCEDURE set_record(p_emp_rec IN emp%ROWTYPE)
IS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO emp
VALUES(p_emp_rec.emp_name,p_emp_rec.emp_no; p_emp_rec.salary,p_emp_re
c.manager);
COMMIT;
END set_record;
FUNCTION get_record(p_emp_no IN NUMBER)
RETURN emp%ROWTYPE
IS
l_emp_rec emp%ROWTYPE;
BEGIN
SELECT * INTO l_emp_rec FROM emp where emp_no=p_emp_no
RETURN l_emp_rec;
END get_record;
BEGIN
dbms_output.put_line(‘Control is now executing the package initialization part');
END pkg_get_set:
/

Output:
Package body created

Step 3) Creating an anonymous block to insert and display the records by referring
to the above created package.

DECLARE
l_emp_rec emp%ROWTYPE;
l_get_rec emp%ROWTYPE;
BEGIN
dbms output.put line(‘Insert new record for employee 1004');
l_emp_rec.emp_no:=l004;
l_emp_rec.emp_name:='CCC';
l_emp_rec.salary~20000;
l_emp_rec.manager:=’BBB’;
pkg_get_set.set_record(1_emp_rec);
dbms_output.put_line(‘Record inserted');
dbms output.put line(‘Calling get function to display the inserted record'):
l_get_rec:=pkg_get_set.get_record(1004);
dbms_output.put_line(‘Employee name: ‘||l_get_rec.emp_name);
dbms_output.put_line(‘Employee number:‘||l_get_rec.emp_no);
dbms_output.put_line(‘Employee salary:‘||l_get_rec.salary');
dbms output.put line(‘Employee manager:‘||1_get_rec.manager);
END:
/

Output:
Insert new record for employee 1004
Control is now executing the package initialization part
Record inserted
Calling get function to display the inserted record
Employee name: CCC
Employee number: 1004
Employee salary: 20000
Employee manager: BBB

5.5 Private versus Public Items in Packages


For objects that are declared inside the package body, you are restricted to use within
that package.
Therefore, PL/SQL code outside the package cannot reference any of the variables
that were privately declared within the package.
Any items declared inside the package specification are visible outside the package
Public is a keyword denoting that that particular item can be accessed outside the
package. Private means that the item will only be used internally in the package.

Example

create or replace package BOOK_MANAGEMENT

as

function OVERDUE_CHARGES(aName IN VARCHAR2) return


NUMBER;

procedure NEW_BOOK (aTitle IN VARCHAR2,


aPublisher IN VARCHAR2, aCategoryName IN VARCHAR2);

end BOOK_MANAGEMENT;

Now the procedure and function here are public and accessible to the outside world.

Now the body, for example

CREATE PACKAGE BODY BOOK_MANAGEMENT AS

number_of_books INT; /*<-- visible only in this


package*/

/*Rest of body blah blah blah*/

END BOOK_MANAGEMENT;

Note above the number of books is private and isn't shown to the user. It is however
(assumed to be) necessary to implement the methods. Similarly, you could have
private functions also.

How to make number_of_books public

create or replace package BOOK_MANAGEMENT

as

number_of_books INT;/*Now its public*/

function OVERDUE_CHARGES(aName IN VARCHAR2) return


NUMBER;

procedure NEW_BOOK (aTitle IN VARCHAR2,

aPublisher IN VARCHAR2, aCategoryName IN VARCHAR2);

end BOOK_MANAGEMENT;

5.6 Package Standard in PL/SQL Environment

A package STANDARD is a built-in package. It defines the datatypes, exceptions,


and subprograms which are available to every PL/SQL program.
The exception NO_DATA_FOUND and functions such as SUBSTR and
TO_CHAR are specified in this package.

For example, package STANDARD declares function ABS, which returns the
absolute value of its argument, as follows:

FUNCTION ABS (n NUMBER) RETURN NUMBER;

The contents of package STANDARD are directly visible to applications. You need
not qualify references to its contents by prefixing the package name. For example,
you might invoke ABS from a database trigger, stored subprogram, Oracle tool, or
3GL application, as follows:

abs_diff := ABS(x - y);

If you declare your own version of ABS, your local declaration overrides the global
declaration. You can still invoke the built-in function by specifying its full name:

abs_diff := STANDARD.ABS(x - y);

Most of the subprograms, such as TO_NUMBER and TO_CHAR is overloaded.


PL/SQL resolves the call by matching the number of arguments and their datatypes.
If user has defined subprograms having the same name, then the original
subprograms can be called using the package name STANDARD, such as
STANDARD.SUBSTR.

5.7 Overview of Product-Specific Packages


Oracle and various Oracle tools are supplied with product-specific packages that
define application programming interfaces (APIs) you can call from PL/SQL, SQL,
Java, or other programming environments.
About the DBMS_ALERT Package
Package DBMS_ALERT lets you use database triggers to alert an application when
specific database values change. The alerts are transaction based and asynchronous
(that is, they operate independently of any timing mechanism). For example, a
company might use this package to update the value of its investment portfolio as
new stock and bond quotes arrive.
About the DBMS_OUTPUT Package
Package DBMS_OUTPUT enables you to display output from PL/SQL blocks,
subprograms, packages, and triggers. The package is especially useful for displaying
PL/SQL debugging information. The procedure PUT_LINE outputs information to
a buffer that can be read by another trigger, procedure, or package. You display the
information by calling the procedure GET_LINE or by setting SERVEROUTPUT
ON in SQL*Plus.
About the DBMS_PIPE Package
Package DBMS_PIPE allows different sessions to communicate over named pipes.
(A pipe is an area of memory used by one process to pass information to another.)
You can use the procedures PACK_MESSAGE and SEND_MESSAGE to pack a
message into a pipe, then send it to another session in the same instance or to a
waiting application such as a UNIX program.
At the other end of the pipe, you can use the procedures RECEIVE_MESSAGE and
UNPACK_MESSAGE to receive and unpack (read) the message. Named pipes are
useful in many ways. For example, you can write a C program to collect data, then
send it through pipes to stored procedures in an Oracle database.
About the HTF and HTP Packages
Packages HTF and HTP allow your PL/SQL programs to generate HTML tags.
About the UTL_FILE Package
Package UTL_FILE lets PL/SQL programs read and write operating system (OS)
text files. It provides a restricted version of standard OS stream file I/O, including
open, put, get, and close operations.
When you want to read or write a text file, you call the function FOPEN, which
returns a file handle for use in subsequent procedure calls. For example, the
procedure PUT_LINE writes a text string and line terminator to an open file, and the
procedure GET_LINE reads a line of text from an open file into an output buffer.
About the UTL_HTTP Package
Package UTL_HTTP allows your PL/SQL programs to make hypertext transfer
protocol (HTTP) callouts. It can retrieve data from the Internet or call Oracle Web
Server cartridges. The package has two entry points, each of which accepts a URL
(uniform resource locator) string, contacts the specified site, and returns the
requested data, which is usually in hypertext markup language (HTML) format.
About the UTL_SMTP Package
Package UTL_SMTP allows your PL/SQL programs to send electronic mails
(emails) over Simple Mail Transfer Protocol (SMTP). The package provides
interfaces to the SMTP commands for an email client to dispatch emails to a SMTP
server.
5.8 Guidelines for Writing Packages
When writing packages, keep them general so they can be reused in future
applications. Become familiar with the Oracle-supplied packages, and avoid writing
packages that duplicate features already provided by Oracle.
Design and define package specs before the package bodies. Place in a spec only
those things that must be visible to calling programs.
To reduce the need for recompiling when code is changed, place as few items as
possible in a package spec. Changes to a package body do not require recompiling
calling procedures. Changes to a package spec require Oracle to recompile every
stored subprogram that references the package.

You might also like