I have a question and I am not finding the answer from google. This may be a simple question since I'm a beginner I have this doubt.
Can we declare a function in Package specification and use the same function for forward declaration ?
CREATE OR REPLACE PACKAGE pckg_test IS FUNCTION fun_test(ID NUMBER) RETURN NUMBER; PROCEDURE proc_test (id number); END pckg_test ; CREATE OR REPLACE PACKAGE BODY pckg_test IS FUNCTION fun_test(ID NUMBER) RETURN NUMBER; --fwd declaration PROCEDURE proc_test (id number) is BEGIN .... calling fun_test .... END; FUNCTION fun_test(ID NUMBER) RETURN NUMBER is BEGIN .... END; END pckg_test; 41 Answer
You can't (forward) declare the function in the body, because it has already been declared in the specification.
This is simple to test with very minor filling-out of your pseudocode:
CREATE OR REPLACE PACKAGE pckg_test IS FUNCTION fun_test(ID NUMBER) RETURN NUMBER; PROCEDURE proc_test (id number); END pckg_test ; / Package PCKG_TEST compiled CREATE OR REPLACE PACKAGE BODY pckg_test IS FUNCTION fun_test(ID NUMBER) RETURN NUMBER; --fwd declaration PROCEDURE proc_test (id number) is x number; BEGIN x := fun_test(1); END; FUNCTION fun_test(ID NUMBER) RETURN NUMBER is BEGIN return 42; END; END pckg_test; / Package Body PCKG_TEST compiled LINE/COL ERROR --------- ------------------------------------------------------------- 2/1 PLS-00305: previous use of 'FUN_TEST' (at line 2) conflicts with this use 2/1 PL/SQL: Item ignored 2/10 PLS-00328: A subprogram body must be defined for the forward declaration of FUN_TEST. Errors: check compiler log The PLS-00305 is because of your forward declaration, which is the same (name and data types) as that in the package specification.
The PLS-00328 is slightly misleading; the full declaration of fun_test seems to be being linked to the public specification, and the forward declaration - even though it is itself throwing an error - then has no matching full declaration.
If you just remove or comment out the forward declaration then it compiles successfully:
CREATE OR REPLACE PACKAGE BODY pckg_test IS --FUNCTION fun_test(ID NUMBER) RETURN NUMBER; --fwd declaration PROCEDURE proc_test (id number) is x number; BEGIN x := fun_test(1); END; FUNCTION fun_test(ID NUMBER) RETURN NUMBER is BEGIN return 42; END; END pckg_test; / Package Body PCKG_TEST compiled You don't need (and are not alowed) a forward declaration of fun_test within the package body because it is publicly declared in the package specification - that public spec makes the function available throughout the package body. So, proc_test can still call fun_test even though it comes first in the body code. The public specification has the same effect as a forward declaration would.
so it means i can give fwd declaration only for private subprograms ?
Yes.
1