Tuesday, January 11, 2011

Oracle PL/SQL Package initialization

The initialization part of PL/SQL package runs only once for a session when you first reference the package. Below i have explained about basics of package initialization with example so that you can understand how & where you can apply this in your application
Here is a small example.

CREATE OR REPLACE PACKAGE init_pack
AS
FUNCTION fun1 RETURN number;
PROCEDURE proc1;
END init_pack;
/

CREATE OR REPLACE PACKAGE BODY init_pack
AS
abc int;
FUNCTION fun1 RETURN number
AS
BEGIN
abc := abc+1;
DBMS_OUTPUT.PUT_LINE('In Function1-abc value is 'abc);
RETURN abc;
END fun1;
PROCEDURE proc1
AS
BEGIN
abc := abc + 1;
DBMS_OUTPUT.PUT_LINE('In proc1- abc values is 'abc);
END proc1;
BEGIN
INSERT INTO test VALUES(1);
COMMIT;
abc :=0 ;
END init_pack;
/
session 1
SQL> exec init_pack.proc1;
In proc1- abc values is 1
PL/SQL procedure successfully completed.
SQL> exec init_pack.proc1;
In proc1- abc values is 2
PL/SQL procedure successfully completed.
SQL> exec init_pack.proc1;
In proc1- abc values is 3
PL/SQL procedure successfully completed.
SQL> select init_pack.fun1 from dual;
FUN1
----------
4
In Function1-abc value is 4
SQL>
-------------------------------------------------------------------------------------------
Here you can notice that the initialization part of a package is run just once, the first time you reference the package. So, in the last example, only one row is inserted into the database table test. The variable abc is initialized only once and every time the procedure proc1 is called, the variable abc is updated. However, the count kept by abc is session specific.

-- The important factors which need to understand --

In the above example, if we reference package by calling the function at the first time in a session, we will get an error. Lets have a look at below.
open a new session- session2
run in the same way below.
SQL> select init_pack.fun1 from dual;
ERROR at line 1:ORA-14551: cannot perform a DML operation inside a query
ORA-06512: at "INIT_PACK", line 24
SQL> select init_pack.fun1 from dual;
FUN1
---------

In Function1-abc value is
SQL> exec init_pack.proc1;
In proc1- abc values is

you might have noticed the above result. If the initilization part of a package contains any DML statement and if we are using the function in a SQL query first time in a session, it will end up with an error. But when you call next time, it will not raise any error but the initialization part won't work even if we call procedure second time.
Think how to resolve this if such kind of situation comes. :)

No comments:

Post a Comment