2 Day Developer > Using Procedures, Functions... > Managing Packages > Accessing Variables in Pack...
Accessing Variables in Packages |
Previous |
Next |
You can create a package specification that is designated only to supply common variables to other packages or subprograms. With the variables in one package, they can be easily maintained for all subprograms that use the variables, rather than maintaining the variables in all the individual subprograms. These common variables are typically used in multiple subprograms, such as a sales tax rate.
In Example: Using Variables in Packages, the variables my_var_pi
, my_var_e
, and my_var_sales_tax
can be used by any subprogram. If you change the value of any of those variables, then all subprograms that use the variable will get the new value without having to change anything in those individual subprograms.
Note that you need to use of the package name as a prefix to the variable name, such as my_var_pkg.my_var_pi
.
Using Variables in Packages
CREATE OR REPLACE PACKAGE my_var_pkg AS -- set up a variable for pi, used in calculations with circles and spheres my_var_pi NUMBER := 3.14016408289008292431940027343666863227; -- set up a variable for e, the base of the natural logarithm my_var_e NUMBER := 2.71828182845904523536028747135266249775; -- set up a variable for the current retail sales tax rate my_var_sales_tax NUMBER := 0.0825; END my_var_pkg; / CREATE OR REPLACE PROCEDURE circle_area(radius NUMBER) IS c_area NUMBER; BEGIN -- the following uses the value of the my_var_pi variable in the my_var_pkg for pi -- in the following calculation of the area of a circle c_area := my_var_pkg.my_var_pi * radius**2; DBMS_OUTPUT.PUT_LINE('Radius: ' || TO_CHAR(radius) || ' Area: ' || TO_CHAR(c_area) ); END circle_area; / BEGIN -- some examples of the use of package constants -- call the circle_area procedure with radius equal to 3, my_var_pi is used to -- calculate the area in circle_area circle_area(3); -- determine the sales tax on a $25 item using my_var_sales_tax for the tax rate DBMS_OUTPUT.PUT_LINE('Sales tax on $25.99 is $' || TO_CHAR(25.99 * my_var_pkg.my_var_sales_tax) ); END; / -- cleanup: drop package and procedure DROP PROCEDURE circle_area; DROP PACKAGE my_var_pkg;