Thursday, March 25, 2010

Global Variables in Packages

I like to say from time to time "I learn something new about Oracle every day".  I am learned something new about PL/SQL that i was not aware of.

scott@10G> create or replace package my_pkg as
  2     procedure p;
  3  end my_pkg;
  4  /

Package created.

Elapsed: 00:00:00.15
scott@10G> create or replace package body my_pkg as
  2     g_global number;
  3
  4     procedure private(l_num in number) as
  5     begin
  6             dbms_output.put_line (' The value of l_num before was '||l_num);
  7             g_global := 65;
  8             dbms_output.put_line (' The value of l_num after was '||l_num);
  9     end;
 10
 11     procedure p as
 12     begin
 13             g_global := 55;
 14             private(g_global);
 15     end p;
 16
 17  end my_pkg;
 18  /

Package body created.

Elapsed: 00:00:00.03
scott@10G> exec my_pkg.p;
 The value of l_num before was 55
 The value of l_num after was 65

PL/SQL procedure successfully completed.

It comes from the fact that IN parameters are passed by reference (as a pointer).The other approach, when FORCED to use globals, assign them to another variable OR cause a temporary to be created (|| '' for strings, +0 for dates, numbers...)

scott@10G> create or replace package my_pkg as
  2     procedure p;
  3  end my_pkg;
  4  /

Package created.

Elapsed: 00:00:00.00
scott@10G> create or replace package body my_pkg as
  2     g_global number;
  3
  4     procedure private(l_num in number) as
  5     begin
  6             dbms_output.put_line (' The value of l_num before was '||l_num);
  7             g_global := 65;
  8             dbms_output.put_line (' The value of l_num after was '||l_num);
  9     end;
 10
 11     procedure p as
 12     begin
 13             g_global := 55;
 14             private(g_global+0);
 15     end p;
 16
 17  end my_pkg;
 18  /

Package body created.

Elapsed: 00:00:00.01
scott@10G> exec my_pkg.p;
 The value of l_num before was 55
 The value of l_num after was 55

PL/SQL procedure successfully completed.

Elapsed: 00:00:00.00

So, one approach is either try to avoid global variables in packages or when Forced to use globals assign them to another variable OR cause a temporary to be created. as i did above.

No comments:

Post a Comment