Thursday, 8 February 2024

Forward Declaration in Procedure

Explain the term "forward declaration" in packages.?

When you have a procedure p2 you want to code for whatever reason AFTER you reference it. 
you can "forward declare it"
For example-

ops$tkyte@ORA920LAP> create or replace package demo_pkg
2 as
3 procedure p;
4 end;
5 /

Package created.

and in the body you have this:



ops$tkyte@ORA920LAP>
ops$tkyte@ORA920LAP> create or replace package body demo_pkg
2 as
3 procedure p
4 is
5 begin
6 p2;
7 end;
8
9 procedure p2
10 is
11 begin
12 null;
13 end;
14 end;
15 /

Warning: Package Body created with compilation errors.

ops$tkyte@ORA920LAP> show errors
Errors for PACKAGE BODY DEMO_PKG:

LINE/COL ERROR
-------- -----------------------------------------------------------------
6/3 PLS-00313: 'P2' not declared in this scope
6/3 PL/SQL: Statement ignored

that fails, p doesn't know about p2 yet, so you can:

ops$tkyte@ORA920LAP>
ops$tkyte@ORA920LAP> create or replace package body demo_pkg
2 as
3 procedure p2;

4
5 procedure p
6 is
7 begin
8 p2;
9 end;
10
11 procedure p2
12 is
13 begin
14  p;
15 end;
16 end demo_pkg;
17 /


Package body created.

forward declare p2, but it would be BETTER to just define p2 at the top of the package

No comments:

Post a Comment