In general, PL/SQL is like other block-structured languages and does not allow forward references. You must declare an identifier before using it. For example, a subprogram must be declared before you can call it.
Coding standards often require that subprograms be kept in alphabetical sequence to make them easy to find. In this case, you may encounter problems.
You can solve the illegal reference problem by reversing the order of the two procedures. However, this easy solution does not work if the coding rules require subprograms to be declared in alphabetical order.
The solution in this case is to use forward declarations provided in PL/SQL. A forward declaration enables you to declare the heading of a subprogram, that is, the subprogram specification terminated by a semicolon.
A forward declaration may be required for private subprograms in the package body, and consists of the subprogram specification terminated by a semicolon. Forward declarations help to:
- Define subprograms in logical or alphabetical order.
- Define mutually recursive subprograms. Mutually recursive programs are programs that call each other directly or indirectly.
- Group and logically organize subprograms in a package body.
When creating a forward declaration:
- The formal parameters must appear in both the forward declaration and the subprogram body.
- The subprogram body can appear anywhere after the forward declaration, but both must appear in the same program unit.
CREATE OR REPLACE PACKAGE PL_TEST AS --Public Procedure Declaration PROCEDURE CALLER; END PLPU04;
CREATE OR REPLACE PACKAGE BODY PL_TEST AS --Forward Declaration PROCEDURE CALC(NUM IN NUMBER); PROCEDURE CALLER AS BEGIN --Reference Resolved CALC(100); END CALLER; --The Implementation PROCEDURE CALC(NUM IN NUMBER) AS BEGIN NULL; END CALC; END PLPU04;When to use Forward Declarations with Packages?
Typically, the subprogram specifications go in the package specification, and the subprogram bodies go in the package body. The public subprogram declarations in the package specification do not require forward declarations.