Sub topic 4
Implementing the package body
This chapter covers how to write a package body that matches its specification, which rules the compiler enforces, and which mistakes show up most often. It assumes you can write basic SQL (SELECT, INSERT, UPDATE), PL/SQL anonymous blocks with variables and control flow, standalone procedures and functions, and basic exception handling. It also assumes you have seen a package specification, which the previous chapter covered.
What the body is
A package body is a separate schema object that holds the code behind a package specification. The specification declares what callers may use. The body supplies the executable code for it.
The body has this layout:
- Private declarations: types, constants, variables, cursors and subprograms that only the body can use.
- Implementations of every subprogram declared in the specification.
- An optional initialization section, which starts with
BEGIN. A later chapter covers it.
A body cannot exist without a specification of the same name in the same schema. You compile the specification first. If you try to create a body for a package that has no specification, Oracle reports a compilation error.
The body is also optional in one case. A specification that declares only constants, types, variables and exceptions needs no body, because there is no code to implement. As soon as the specification declares a subprogram, a cursor with a RETURN clause, or any other item that needs code, a body is required.
A body that matches its specification
Start with the specification below. It declares a constant, an exception and two subprograms.
CREATE OR REPLACE PACKAGE emp_api AS
c_max_raise_pct CONSTANT NUMBER := 20;
e_raise_too_large EXCEPTION;
PRAGMA EXCEPTION_INIT(e_raise_too_large, -20001);
FUNCTION get_salary(p_employee_id IN employees.employee_id%TYPE)
RETURN employees.salary%TYPE;
PROCEDURE raise_salary(
p_employee_id IN employees.employee_id%TYPE,
p_pct IN NUMBER);
END emp_api;
/The body implements both subprograms and adds one private helper.
CREATE OR REPLACE PACKAGE BODY emp_api AS
-- Private: not declared in the specification, so callers cannot see it.
FUNCTION is_valid_pct(p_pct IN NUMBER) RETURN BOOLEAN IS
BEGIN
RETURN p_pct > 0 AND p_pct <= c_max_raise_pct;
END is_valid_pct;
FUNCTION get_salary(p_employee_id IN employees.employee_id%TYPE)
RETURN employees.salary%TYPE IS
l_salary employees.salary%TYPE;
BEGIN
SELECT salary INTO l_salary
FROM employees
WHERE employee_id = p_employee_id;
RETURN l_salary;
END get_salary;
PROCEDURE raise_salary(
p_employee_id IN employees.employee_id%TYPE,
p_pct IN NUMBER) IS
BEGIN
IF NOT is_valid_pct(p_pct) THEN
RAISE e_raise_too_large;
END IF;
UPDATE employees
SET salary = salary * (1 + p_pct / 100)
WHERE employee_id = p_employee_id;
END raise_salary;
END emp_api;
/Several points are worth noticing.
- The body does not repeat
c_max_raise_pctore_raise_too_large. Everything in the specification is already visible inside the body, sois_valid_pctreads the constant directly andraise_salaryraises the exception directly. is_valid_pctappears only in the body. Code outside the package cannot call it.- The body starts with
CREATE OR REPLACE PACKAGE BODY, and both parts end with the package name afterEND.
Callers reach only the public items:
BEGIN
emp_api.raise_salary(100, 10);
DBMS_OUTPUT.PUT_LINE('New salary: ' || emp_api.get_salary(100));
EXCEPTION
WHEN emp_api.e_raise_too_large THEN
DBMS_OUTPUT.PUT_LINE('Raise exceeds ' || emp_api.c_max_raise_pct || '%');
END;
/Calling emp_api.is_valid_pct(10) from this block fails with PLS-00302: component 'IS_VALID_PCT' must be declared.
Rules the compiler enforces
Oracle compares each subprogram header in the body with the one in the specification. The headers must agree token by token, apart from whitespace and letter case. Four things must match:
- The subprogram name.
- The number, names and order of parameters.
- The parameter modes (
IN,OUT,IN OUT). - The parameter datatypes and, for functions, the return datatype.
Default values are part of the specification only. You write p_pct IN NUMBER DEFAULT 5 in the specification, and the body header omits the default. Writing it in both places is an error.
Here is a body that does not match. The specification says p_pct IN NUMBER, but the body has changed the parameter name:
CREATE OR REPLACE PACKAGE BODY emp_api AS
FUNCTION get_salary(p_employee_id IN employees.employee_id%TYPE)
RETURN employees.salary%TYPE IS
l_salary employees.salary%TYPE;
BEGIN
SELECT salary INTO l_salary
FROM employees
WHERE employee_id = p_employee_id;
RETURN l_salary;
END get_salary;
PROCEDURE raise_salary(
p_employee_id IN employees.employee_id%TYPE,
p_percent IN NUMBER) IS
BEGIN
NULL;
END raise_salary;
END emp_api;
/Oracle compiles this with errors. A typical message is PLS-00323: subprogram or cursor 'RAISE_SALARY' is declared in a package specification and must be defined in the package body, often together with PLS-00328, because the body's raise_salary is treated as a different, private subprogram. The specification's version then has no implementation.
Run SHOW ERRORS PACKAGE BODY emp_api in SQL*Plus or SQLcl, or query USER_ERRORS, to see the full list:
SELECT line, position, text
FROM user_errors
WHERE name = 'EMP_API'
AND type = 'PACKAGE BODY'
ORDER BY sequence;Two rules follow from this.
- Every subprogram declared in the specification must be defined in the body. A missing one causes PLS-00323.
- A subprogram defined in the body but not declared in the specification is private. This is how you create private helpers, and it is also how a typo in a header silently creates a private subprogram instead of an implementation.
Parameter types written with %TYPE are compared by what they refer to, so employees.employee_id%TYPE in both places matches. Writing NUMBER in one place and employees.employee_id%TYPE in the other is rejected, even if the column is a NUMBER. Copy the header from the specification to avoid this.
Order of declarations inside the body
PL/SQL requires a name to be declared before it is used. Inside a body, this applies to private subprograms. If raise_salary calls is_valid_pct, then is_valid_pct must appear earlier in the body, or be forward-declared.
This is why the example places the private function first. Public subprograms declared in the specification are exempt, because the specification is processed before the body. A private subprogram can call any public one regardless of position.
When two private subprograms call each other, neither can come first. A forward declaration solves this. It repeats the header of one subprogram, ending with a semicolon, before the other uses it:
CREATE OR REPLACE PACKAGE parity AS
FUNCTION is_even(p_n IN PLS_INTEGER) RETURN BOOLEAN;
END parity;
/
CREATE OR REPLACE PACKAGE BODY parity AS
-- Forward declaration: is_even calls is_odd before is_odd is defined.
FUNCTION is_odd(p_n IN PLS_INTEGER) RETURN BOOLEAN;
FUNCTION is_even(p_n IN PLS_INTEGER) RETURN BOOLEAN IS
BEGIN
IF p_n = 0 THEN
RETURN TRUE;
END IF;
RETURN is_odd(p_n - 1);
END is_even;
FUNCTION is_odd(p_n IN PLS_INTEGER) RETURN BOOLEAN IS
BEGIN
IF p_n = 0 THEN
RETURN FALSE;
END IF;
RETURN is_even(p_n - 1);
END is_odd;
END parity;
/A later chapter treats forward declarations in more depth. For now, remember that the rule is about declaration order and that the body is where you hit it.
Private declarations in the body
The body can declare more than subprograms. Constants, types, cursors, variables and exceptions declared there are private. Declare them before the subprograms that use them.
CREATE OR REPLACE PACKAGE BODY emp_api AS
-- Private constant, type and variable
c_audit_enabled CONSTANT BOOLEAN := TRUE;
TYPE t_id_list IS TABLE OF employees.employee_id%TYPE;
g_last_id employees.employee_id%TYPE;
FUNCTION get_salary(p_employee_id IN employees.employee_id%TYPE)
RETURN employees.salary%TYPE IS
l_salary employees.salary%TYPE;
BEGIN
SELECT salary INTO l_salary
FROM employees
WHERE employee_id = p_employee_id;
g_last_id := p_employee_id;
RETURN l_salary;
END get_salary;
PROCEDURE raise_salary(
p_employee_id IN employees.employee_id%TYPE,
p_pct IN NUMBER) IS
BEGIN
IF p_pct <= 0 OR p_pct > c_max_raise_pct THEN
RAISE e_raise_too_large;
END IF;
UPDATE employees
SET salary = salary * (1 + p_pct / 100)
WHERE employee_id = p_employee_id;
END raise_salary;
END emp_api;
/Keeping these private has a practical benefit. You can change t_id_list or remove g_last_id later without affecting any caller, because no caller could have referred to them. Anything you put in the specification becomes a commitment.
g_last_id is also package state. It keeps its value for the rest of the session, which a later chapter on package state covers.
Name resolution inside the body
Inside the body, an unqualified name is resolved in this order: the local block, then the enclosing subprogram, then the package body, then the specification, then the schema. A local variable named like a column can cause surprises in SQL statements.
Inside a SQL statement, a column name wins over a PL/SQL variable of the same name. This is a classic bug:
PROCEDURE raise_salary(
employee_id IN employees.employee_id%TYPE,
p_pct IN NUMBER) IS
BEGIN
UPDATE employees
SET salary = salary * (1 + p_pct / 100)
WHERE employee_id = employee_id; -- always true: compares the column to itself
END raise_salary;The WHERE clause compares the column with itself, so every row is updated. The p_ prefix convention on parameters avoids the clash. You can also qualify the parameter with the subprogram name, as in raise_salary.employee_id.
Recompiling the body
You can recompile the body alone, without touching the specification:
ALTER PACKAGE emp_api COMPILE BODY;Or replace it with CREATE OR REPLACE PACKAGE BODY. Because callers depend on the specification and not on the body, this normally leaves other objects valid. The chapter on dependencies explains the exact rules.
If the body has compile errors, the package is left in an invalid body state. The specification stays valid, but calling any subprogram raises ORA-04068 or ORA-06508 until the body compiles cleanly.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| PLS-00323 when compiling the body | A subprogram in the specification has no matching definition in the body | Add it, or fix the header so it matches |
| PLS-00302 when calling a subprogram | The subprogram exists only in the body, so it is private | Declare it in the specification |
| PLS-00313 or PLS-00201 inside the body | A private subprogram is used before it is declared | Reorder, or add a forward declaration |
| Body compiles but behaves as if a header is missing | A typo in a parameter name or type created a different private subprogram | Copy the header from the specification |
| Update or delete affects every row | A parameter or variable has the same name as a column | Prefix parameters with `p_` or qualify the name |
Design guidance
- Copy headers from the specification instead of retyping them.
- Put private helpers at the top of the body, in dependency order, so you need few forward declarations.
- Keep the specification as small as you can. Anything you can keep private stays free to change.
- Compile the specification and the body as one script, with the specification first.
Exercise
A specification declares PROCEDURE log_msg(p_text IN VARCHAR2);. The body defines PROCEDURE log_msg(p_message IN VARCHAR2) IS BEGIN NULL; END;. The body fails to compile. Why, and how do you fix it?
Show answer
The parameter name in the body (pmessage) differs from the one in the specification (ptext), so Oracle treats the body procedure as a different private subprogram and reports that the specification's logmsg has no definition (PLS-00323). Change the body header to use ptext, ideally by copying the header from the specification.
Exercise
You write a private function format_name in the body after a public procedure that calls it. The body fails to compile. Give two ways to fix this.
Show answer
Move formatname above the procedure that calls it, or add a forward declaration of formatname (its header followed by a semicolon) before the procedure. A private subprogram must be declared before it is used.