HomeOracle Page 5 - Database Interaction with PL/SQL, User-defined Packages
How the above package works - Oracle
This article is part of a series focusing on database interactions with Oracle PL/SQL. In my previous article, we examined named notation, default values of parameters, stored procedures, stored functions and finally took our first look at package and package body. In this article, we will focus completely on package and package body. Before reading this article I suggest you to go through my last three articles in this series thoroughly.
The above two are overloaded sub-programs. One sub-program has a single parameter and the other does not have any parameters. That’s the end of the package specification. Now, let us see about the package body.
procedure dispEmp as cursor c_emp is select ename, sal from emp; r_emp t_emprec; begin open c_emp; loop fetch c_emp into r_emp; exit when c_emp%notfound; dbms_output.put_line(r_emp.name || ',' || r_emp.salary); end loop; close c_emp; end;
The above procedure is very similar to the one given in the third section of the article. It just displays all employee names and salaries. The only difference is that it fetches the information into a record based variable of type ‘t_emprec’ which was declared in the package specification.
procedure dispEmp(p_deptno dept.deptno%type) as cursor c_emp is select ename, sal from emp where deptno = p_deptno; r_emp t_emprec; begin open c_emp; loop fetch c_emp into r_emp; exit when c_emp%notfound; dbms_output.put_line (r_emp.name || ',' || r_emp.salary); end loop; close c_emp; end;
I hope you can understand the above sub-program as it is quite similar except in the case of parameter declaration.
Other extensions to package development
One more point to understand is that you can also have some declarations within the package body straight away. That means you can have the declarations at the top of package body (without having any relation to the sub-programs). Once you have such declarations, those are called private declarations within the package. That means you can use all of those declarations in each of the sub-programs available.
Such types of package body level variable declarations are generally used to implement security within the package context (hiding it from outside world).
Even though I didn’t use any functions in any of the above packages, it doesn’t mean that you shouldn’t use them. You can use them as freely as you wish. And another great feature is that you can call another sub-program within the same sub-program without specifying the package name. Of course you are also allowed to call the sub-programs which are outside the package as well.