Use in Oracle
The main purpose of using a package is to modularize the program. The package can combine the relevant stored procedures, functions, variables, constants, cursors, and other PL/SQL programs, in this way, code libraries can be constructed for reuse by programmers. In addition, when the stored procedure or function element in the package is called for the first time, Oracle transfers the entire package to the memory. When the elements in the package are called for the next time, Oracle can read them from the memory, this improves the program running efficiency.
The package consists of the package specification and package body. Where,
The package specification is used to list the available stored procedures, functions, cursors, and other element entries (actual code without these elements) in the package. These entries are public projects and can be accessed by all database users.
The package body contains the actual code of the element. You can also create a project not mentioned in the specification in the package body. All these projects are private projects, it can only be used in the package body.
Create a package specification
The create package statement is required to CREATE a PACKAGE specification. Its syntax is as follows:
CREATE [OR REPLACE] PACKAGE package_name {IS|AS} package_specification; END package_name;
-Package_name: package_specification is used to list public stored procedures, functions, types, and objects that can be used by users.
Create a package
To CREATE a package body, you must use the create package body statement and specify the PACKAGE you have created when creating the PACKAGE. The syntax is as follows:
CREATE [OR REPLACE] PACKAGE BODY package_name {IS|AS} package_body END package_name;
Instance
The specific example is as follows:
1. Create a package specification
CREATE OR REPLACE PACKAGE common_pkg IS FUNCTION tax(value IN NUMBER) RETURN NUMBER; END common_pkg;
2. Create a package
CREATE OR REPLACE PACKAGE BODY common_pkg IS FUNCTION tax(value IN NUMBER) RETURN NUMBER IS rate NUMBER:=0.08; BEGIN RETURN (value*rate); END tax; END common_pkg;
Call the functions in the package,
SELECT common_pkg.tax(sal) FROM emp;