Вы находитесь на странице: 1из 18

Lesson 8

Packages
Lesson 8 -Packages Copyright 1999, Pinnacle Software Solutions Inc.

8.0

Lesson 8: Packages

8.1 Lesson Objectives

Le s s o nO b je c tiv e s
Lesson 8 -Packages

In this lesson students will learn about: Package structure & advantages Creation of packages Using packages in a PL/SQ L program
Copyright 1999, Pinnacle Software Solutions Inc.

8 .1

Introduction: This chapter introduces PL/SQL packages. A Package is a collection of elements such as procedures, functions, variables, constants, cursors, exceptions. These elements are encapsulated in the package. A package is of two parts: Specification Body Packages may be either built-in or user-defined. The user must create userdefined packages whereas built-in packages are pre-defined by Oracle. Some of the Oracle built-in packages are: DBMS_PIPE: Enables communication between synchronous sessions DBMS_OUTPUT: Provides screen output in SQL*Plus or Server Manager

PL /SQL Programming 8-1

1999, Pinnacle Software Solutions, Inc.

Lesson 8: Packages

8.2 About Packages

P a c k a g e
Lesson 8 -Packages

Is a nam ed block com prising specification & body Is stored in the database Contains related objects stored as a single unit Can contain procedures, functions, constants, variables, cursors or exceptions
Copyright 1999, Pinnacle Software Solutions Inc.

8.2

Packages are named PL/SQL blocks consisting of a package specification and a package body. Unlike procedures or functions, packages cannot be locally contained in a block and are stored in the database. Packages contain related objects, which are stored together within a unit. Package objects can be procedures, functions, constants, variables (scalar or composite), cursors or exceptions.

PL/ SQL Programming 8-2

1999, Pinnacle Software Solutions, Inc.

Lesson 8: Packages

8.3 Advantages Of Using Packages

A d v a n ta g e s
Lesson 8 -Packages

Modularity Inform ation Hiding Persistent data Perform ance

Copyright 1999, Pinnacle Software Solutions Inc.

8.3

Although packages are deceptively simple to create, they are powerful PL/SQL constructs. Packages offer:

Modularity: Encapsulating related PL/SQL program units and objects Information Hiding: Declaring package objects as public or private Persistent data: Retaining package variables and cursors for the duration of the session Performance: Loading the entire package into memory when one of its elements is referred to

PL/ SQL Programming 8-3

1999, Pinnacle Software Solutions, Inc.

Lesson 8: Packages

8.4 Creating a Package

D e c la rin gP a c k a g e s
Lesson 8 -Packages

In the specification for PUBLIC objects Syntax: CREATE [O R REPLACE] PACKAG E schem a.package_nam e IS | AS PL/SQ L specification; ENDpackage_nam e;

Copyright 1999, Pinnacle Software Solutions Inc.

8 .4

A package specification and body are created as two separate units. CREATE PACKAGE may only be used by a user with CREATE PROCEDURE or CREATE ANY PROCEDURE privileges. Specification: A package specification contains the declarations of PUBLIC package objects, which can be accessed by: External procedures Statements issued by the owner of the package A user with EXECUTE privileges for the package Syntax: CREATE [OR REPLACE] PACKAGE schema.package_name IS | AS PL/SQL specification; END package_name; Where: Package_name is the name of the package. Schema is the name of the package owners schema.

PL/ SQL Programming 8-4

1999, Pinnacle Software Solutions, Inc.

Lesson 8: Packages
Example: The ClassOperations package specification consists of a PL/SQL table type, a cursor, two procedures and a function: CREATE OR REPLACE PACKAGE ClassOperations AS -- Global variable declaration Student_count number(3); -- Table type to hold cities information TYPE Cities IS TABLE OF Varchar2(32) INDEX BY Binary_Integer; -- Retrieves information about all students CURSOR student_cur RETURN student%rowtype; -- Displays relevant class information PROCEDURE Display_Class_Info (Class_id_in IN NUMBER); -- Provides a course fee PROCEDURE Display_course_fee (Course_id_in IN NUMBER, Course_fee_out OUT NUMBER); -- Returns a students outstanding balance FUNCTION Compute_Student_Balance RETURN NUMBER; END ClassOperations; Note: The new feature in 8i allows the declaration of a cursor in a package specification with a RETURN clause in lieu of OPEN, FETCH and CLOSE commands. The cursor RETURN clause may be either a table-based or programmerdefined record declaration.

PL/ SQL Programming 8-5

1999, Pinnacle Software Solutions, Inc.

Lesson 8: Packages

Fig.1 Creating or Declaring a Package Oracle issues a message informing that the package specification has been created.

PL/ SQL Programming 8-6

1999, Pinnacle Software Solutions, Inc.

Lesson 8: Packages

8.5 Defining Package Objects

P a c k a g eB o d y
D efines objects declared in specification Package objects m ay be referenced from other program s Package objects if PRIVATE can be referenced only within the package
Lesson 8 -Packages Copyright 1999, Pinnacle Software Solutions Inc.

8.5

A package body contains the definition of all package objects declared in the package specification. These are PUBLIC or GLOBAL package objects, visible outside the package body and available to programs outside this scope that refer to them. The body will also contain PRIVATE or local package objects declared within the scope of the package body. However, these can only be used within the body by other package elements. Syntax: CREATE PACKAGE BODY schema.package_name IS | AS PL/SQL blocks; BEGIN {Optional INITIALIZATION Section} END package_name;

PL/ SQL Programming 8-7

1999, Pinnacle Software Solutions, Inc.

Lesson 8: Packages
Example: The ClassOperations package body follows: CREATE OR REPLACE PACKAGE BODY ClassOperations AS -- Local exception declaration Invalid_Fee EXCEPTION; -- Table type to hold all cities information Cities_Table Cities; -- Retrieves information about all students CURSOR student_cur RETURN student%rowtype IS SELECT * FROM student; -- Displays relevant information on a class PROCEDURE Display_Class_Info (Class_id_in IN NUMBER) IS Class_location Class.Location%TYPE; Class_Start_Date Class.Start_Date%TYPE; BEGIN Select Location, Start_Date Into Class_Location, Class_Start_Date From Class Where Class_id = Class_id_in; Dbms_output.Put_line(Class #|| Class_id_in || will be taught in || Class_Location || on || Class_Start_Date); END; -- Provides a course fee PROCEDURE Display_course_fee (Course_id_in IN NUMBER, Course_fee_out OUT NUMBER) IS BEGIN Select Course_fee into Course_fee_out From Course Where course_id = Course_id_in; END; -- Returns a students outstanding balance FUNCTION Compute_Student_Balance RETURN NUMBER IS CURSOR Balance_cur IS SELECT Course_fee, Fee_paid, Student_id, Class.Class_Id FROM Course, Registration, Class Where Course.course_id = Class.course_id and Class.class_id = Registration.class_id and student_id = 104; Balance_Due NUMBER;

PL/ SQL Programming 8-8

1999, Pinnacle Software Solutions, Inc.

Lesson 8: Packages
BEGIN Balance_Due:=0; FOR Balance_rec IN Balance_cur LOOP Balance_Due:=Balance_Due + Balance_rec.Course_fee Balance_rec.Fee_Paid; END LOOP; Return Balance_Due; END; END ClassOperations; Note: Invalid_fee is a private object unlike all others in this package. Oracle issues a message on the screen on creation of the package body.

Fig.2 Defining the Objects in the Package Body

PL/ SQL Programming 8-9

1999, Pinnacle Software Solutions, Inc.

Lesson 8: Packages

8.6 On Using Packages

U s in gP a c k a g e s
Packages own elem ents as tables own colum ns Use dot notation to use a public object in a package e.g. Package_nam e.object_nam e;
Lesson 8 -Packages Copyright 1999, Pinnacle Software Solutions Inc.

8.6

To use a public object in a package from a program, use the dot notation to prefix the object name with the package name. Syntax: Package_name.object_name; Example: To display information regarding class number 113, the statement is: BEGIN ClassOperations.Display_Class_Info(113); END;

PL/ SQL Programming 8 - 10

1999, Pinnacle Software Solutions, Inc.

Lesson 8: Packages
The screen output follows:

Fig.3 Calling a Procedure of a Package When using predefined Oracle packages such as DBMS_PIPE and DBMS_OUTPUT, use the same dot notation. Example: DBMS_OUTPUT.PUT_LINE is used to generate output from program units

PL/ SQL Programming 8 - 11

1999, Pinnacle Software Solutions, Inc.

Lesson 8: Packages

8.7 About Package Initialization

P a c k a g eIn itia liz a tio n


O ccurs the first tim e a package elem ent is referred to in a program Is an optional section, executed only once
Lesson 8 -Packages Copyright 1999, Pinnacle Software Solutions Inc.

8.7

Package instantiation is the loading of the entire package into memory when one of its elements is first referred to in a program, making all its components available. In case of global variables, they must be initialized in the initialization section in the package body. The package initialization section is optional and is the last section in the package body following the defining of the other program units. It is executed once only. Such sections are also known as one-time only procedures. Example: CREATE OR REPLACE PACKAGE BODY ClassOperations AS -- Declaration of local and public package objects /* Initialization section*/ BEGIN SELECT COUNT(*) INTO Student_count FROM STUDENT; END ClassOperations;

PL/ SQL Programming 8 - 12

1999, Pinnacle Software Solutions, Inc.

Lesson 8: Packages

8.8 The Overloading Feature

O v e rlo a d in g

Is when programunits in a package have sam e nam e but different param eter num bers, ordering sequence or datatypes When executed, O racle com piler com pares actual with form al param eters Com pilation results in an error when no m atch is found Lesson 8 -Packages Copyright 1999, Pinnacle Software Solutions Inc.
8.8

Overloading is a feature of packages. It allows one operation to be applied on different object types. It occurs when several program units in a package have the same name, but different parameter numbers, ordering sequence and datatypes (type families). The Oracle compiler compares the actual parameters, in the procedure or function call, with the formal parameter list in the declaration, looking for an exact match. Errors result when no matches are found.

PL/ SQL Programming 8 - 13

1999, Pinnacle Software Solutions, Inc.

Lesson 8: Packages
Example: The ClassOverload package specification and body provide an example of overloading. They reuse the Display_Course_Fee procedures declared with and without parameters, in Lesson 6. CREATE OR REPLACE PACKAGE ClassOverload AS -- Displays the fee of course 112 PROCEDURE Display_course_fee; -- Displays any course fee PROCEDURE Display_course_fee (Course_id_in IN NUMBER, Course_fee_out OUT NUMBER); END ClassOperations; / CREATE OR REPLACE PACKAGE BODY ClassOverload AS -- Displays the fee of course 112 CREATE OR REPLACE PROCEDURE Display_course_fee IS Local_fee Course.Course_fee%TYPE; BEGIN Select Course_fee into Local_fee From Course Where course_id = 112; Dbms_output.Put_line(This courses fee is of $||Local_fee); END; -- Provides a course fee PROCEDURE Display_course_fee (Course_id_in IN NUMBER, Course_fee_out OUT NUMBER) IS BEGIN Select Course_fee into Course_fee_out From Course Where course_id = Course_id_in; END; END ClassOperations;

PL/ SQL Programming 8 - 14

1999, Pinnacle Software Solutions, Inc.

Lesson 8: Packages

8.9 Summary

S u m m a ry

Packages: Are nam ed PL/SQ L blocks Can separate specification & body for data hiding Contain public or private objects With public com ponents are prefixed by package nam e With global variables are initialized in the initialization section Support overloading
Lesson 8 -Packages Copyright 1999, Pinnacle Software Solutions Inc.

8.9

Packages are named PL/SQL blocks, which allow the encapsulation of related objects such as procedures, functions, cursors, variables, and exceptions. A package comprises a package specification and a package body. These are created separately to support information hiding.

Package objects can be private or public: PUBLIC package objects are declared in the package specification and can be used from programs outside the package scope. PRIVATE package objects are declared in the package body but can only be used by other package body elements. To use public package components from external programs, use the dot notation to prefix the object name with the package name. A package initialization section may be used to initialize global package variables.

PL/ SQL Programming 8 - 15

1999, Pinnacle Software Solutions, Inc.

Lesson 8: Packages
Overloading is the ability to use the same name for program units with different parameter numbers, ordering sequence and datatypes within the same package. When called, Oracle compiler compares actual with formal parameters to find a match for execution.

PL/ SQL Programming 8 - 16

1999, Pinnacle Software Solutions, Inc.

Lesson 8: Packages

Lesson 8 Exercises
1. Create a package specification and body consisting of the procedures and functions defined in the exercises section at 6. Call this package CLASS. Create a procedure named set_comm to conditionally set the commission for a given sales person based on total sales. Create a parameter to pass the sales persons id. Find the salary for that sales person. If the salary is less than 20000, increase the commission of the Sales person by 1.5. If the salary is between 20000 and 30000 inclusive, increase the commission of the sales person by 2. If the salary exceeds 30000, increase the commission by 2.5. Create a Procedure named TOP_DOGS that determines the top sales persons with respect to salaries. Prepare for this exercise by creating a new table for storing sales persons names and their salaries. CREATE TABLE top_dogs (name varchar2(25), salary number(11,2)); Add a parameter to allow the user to pass an input n for the top number of employees. Write a cursor FOR loop to get the last_names and salaries of the top n people, with respect to salary, from the sales_person table. Store the names and salaries in the TOP_DOGS table. Assume for the moment that no two employees have the same salary. Create a Function sales_sal to return annual salary of a sales person by passing sales person id as the parameter. Create and execute a procedure named MULTIPLIER that accepts three variables. The first number should be divided by the second number and have the second number added to the result

2. Write a simple PL/SQL program to execute the function sales_sal within this package and display the results.

PL/ SQL Programming 8 - 17

1999, Pinnacle Software Solutions, Inc.

Вам также может понравиться