Pages

Sunday, September 18, 2011

Packages in PL/SQL

Packages have objects (they own them as tables own their columns).
Objects can be (not limited to):

  1. packages
  2. functions
  3. variables
Think of a package in pl/sql as a logical grouping. For example, if there's a students package, it may have::
  • a package variable that reflects if the study term is open or not
  • procedures that process time table allocations ( does not need to return any value and runs after work hours in batch mode) 
  • functions that return statistics of students. For example, counts of local, interstate and overseas students in a given semester
Example:

CREATE OR REPLACE PACKAGE BODY students_pkg
IS 

   term_active  ....

   PROCEDURE allocate_timetables
   .....

   FUNCTION get_local_students_count
       ....
   RETURN count NUMBER;
       ....

   FUNCTION get_overseas_students_count
       ....
   RETURN count NUMBER;
       ....

   FUNCTION get_interstate_students_count
       ....
   RETURN count NUMBER;
       ....

  BEGIN 
     -- initialisation codes live here
     -- assign default values to objects here
     -- execute whatever logic/code here
  END students-pkg;


Outside the package, we use it...



DECLARE
    ...

BEGIN

    IF students_pkg.terms THEN
       DBMS_OUTPUT.PUT_LINE( "Number of local students in this term is " || students_pkg.get_local_students_count );
    END IF;

EXCEPTION
      ...
END;