- Explain stored procedures and functions and their advantages.
- Create, execute, inspect (USER_SOURCE, SHOW ERRORS) and recompile them.
- Distinguish formal and actual parameters and use IN, OUT and IN OUT modes with NOCOPY.
- Compare definer rights and invoker rights (AUTHID CURRENT_USER).
- Raise application errors with RAISE_APPLICATION_ERROR.
- Create packages with a specification, a body and an initialisation part.
Stored Procedures and Functions
A stored procedure (database procedure) is a named PL/SQL block stored in the database as an object and invoked by name; it may take parameters. A function is the same but returns a value that the caller uses.
| Advantage | Why |
|---|---|
| Reduced network traffic | The client sends only the procedure name, not the whole block. |
| Better performance | Stored in compiled form next to the data – no compilation at run time; shared memory lets a second user find the procedure already in memory. |
| Easy maintenance | Business logic is changed once in the procedure; all clients use the new version – improving integrity and consistency. |
| Security | Users get EXECUTE on the procedure but no access to the underlying tables; the procedure runs with the owner’s privileges. |
create or replace procedure newpayment(rollno number, amt number) is
begin
insert into payments values (rollno, sysdate, amt);
commit;
end;
/
SQL> execute newpayment(10, 2000);
create or replace function getdueamt(prollno number) return number is
v_fee number(5);
v_amtpaid number(5);
begin
select sum(amount) into v_amtpaid from payments where rollno = prollno;
select fee into v_fee from courses
where ccode = ( select ccode from batches
where bcode in ( select bcode from students where rollno = prollno ) );
return v_fee - v_amtpaid;
end;
/
SQL> select rollno, getdueamt(rollno) from students; -- used like ROUND or SUBSTR- Oracle creates a procedure even when it has errors (Warning: Procedure created with compilation errors) – use SHOW ERRORS and re-create it with OR REPLACE.
- EXECUTE runs a procedure; you must own it or have the EXECUTE privilege.
- Source code is in USER_SOURCE (
where name = 'NEWPAYMENT'). - Creating needs the CREATE PROCEDURE system privilege plus object privileges on referenced objects – granted directly, not through roles.
Recompiling
Procedures are stored compiled. If one becomes INVALID (e.g. SCOTT’s procedure lacked INSERT on BOOK.PAYMENTS), Oracle recompiles it implicitly on next use; to avoid that run-time cost recompile explicitly:
alter procedure newpayment compile; alter function getdueamt compile; select status from user_objects where object_name = 'NEWPAYMENT'; -- VALID
Parameters and Parameter Modes
- Formal parameters – declared in the procedure definition (
pccode, pamt); they receive values. - Actual parameters – the values given in the call (
v_ccode, 2000); copied to the formal parameters.
| Mode | Behaviour | Actual parameter |
|---|---|---|
| IN (default) | Passes a value in; acts like a constant – cannot be assigned | Variable, constant or expression |
| OUT | Returns a value to the caller; uninitialised inside the subprogram | Must be a variable |
| IN OUT | Receives a value and returns a value | Must be a variable |
create or replace procedure get_dates( pccode in varchar2,
first_date out date,
last_date out date ) is
begin
select min(stdate) into first_date from batches where ccode = pccode;
select max(stdate) into last_date from batches where ccode = pccode;
end;
/
declare
min_date date;
max_date date;
begin
get_dates('ora', min_date, max_date);
dbms_output.put_line(min_date || ':' || max_date);
end;12-JAN-01:15-AUG-01
NOCOPY: OUT and IN OUT parameters are passed by value by default (copied in and back out). For large structures (records, objects) the NOCOPY hint passes them by reference, saving time and memory: procedure change(pstudent in out nocopy student_type).
Definer Rights vs Invoker Rights
| Definer (owner) rights – default | Invoker rights – AUTHID CURRENT_USER (Oracle8i) | |
|---|---|---|
| Privileges used | Owner’s | Calling user’s |
| Unqualified objects resolve to | Owner’s schema (SRIKANTH.MESSAGES) | Invoker’s schema (PRANEETH.MESSAGES – ORA-00942 if missing) |
| Benefit | Users need only EXECUTE; tables stay protected | Centralised code, data kept in each user’s own schema |
RAISE_APPLICATION_ERROR
Creates your own application error number and message, terminates the program and sends the error to the host. The notes give the error number range as -20001 to -20999 (Oracle’s documentation states the reserved range as -20000 to -20999).
exception
when no_data_found then
raise_application_error(-20100, 'Invalid course code');Packages
A package is a collection of related procedures, functions, variables and datatypes identified by one name (which also avoids name conflicts). It has two parts:
- Specification – declares the public items, callable from outside as
package_name.object_name. - Body – defines the public procedures/functions and cursors, plus private procedures, functions and variables used only inside the package. An optional initialisation part (BEGIN … at the end of the body) runs when a user first refers to the package.
create or replace package course_pkg as
procedure changefee (pccode varchar2, newfee number);
function getbatchcourse (pbcode varchar2) return varchar2;
end;
/
create or replace package body course_pkg as
procedure changefee (pccode varchar2, newfee number) is
begin
update courses set fee = newfee where ccode = pccode;
if sql%found then
commit;
else
raise_application_error(-20010, 'Invalid course code');
end if;
end;
function getbatchcourse (pbcode varchar2) return varchar2 is
v_ccode courses.ccode%type;
begin
select ccode into v_ccode from batches where bcode = pbcode;
return v_ccode;
exception
when no_data_found then
raise_application_error(-20011, 'Invalid batch code');
end;
end;
/
SQL> execute course_pkg.changefee('ora', 5000);- Procedures do work; functions return a value and can be used in SQL.
- IN is the default mode; OUT/IN OUT need variables; NOCOPY passes by reference.
- Definer rights by default; AUTHID CURRENT_USER for invoker rights.
- Packages = public specification + body with private members and optional initialisation.
Chapter 19 Notes (PDF)
Question / Answer (15 questions)
Moderate-level questions based on the Chapter 19 notes (PDF). Click a question to see the answer.
MCQ Test : Check Your Understanding (5 questions)
Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.
Bibliography/References
The chapter notes PDF is the course study material and is credited to its author below. The explanations, questions and MCQs on this page are original study aids written for this course from the topics covered in that PDF. The other works are cited for verification and further reading. Oracle, SQL*Plus and PL/SQL are trademarks of Oracle Corporation; other names belong to their respective owners.
- Srikanth, P. (n.d.). Oracle For Beginners (chapter notes – the PDF shown on each chapter page). Srikanth Technologies. http://www.srikanthtechnologies.com/
- Oracle Corporation. (n.d.). Oracle Database PL/SQL Language Reference, 19c. https://docs.oracle.com/en/database/oracle/oracle-database/19/lnpls/
- Oracle Corporation. (n.d.). Oracle Database Development Guide, 19c. https://docs.oracle.com/en/database/oracle/oracle-database/19/adfns/
- Oracle Corporation. (n.d.). Oracle Database Security Guide, 19c. https://docs.oracle.com/en/database/oracle/oracle-database/19/dbseg/
- Feuerstein, S., & Pribyl, B. (2014). Oracle PL/SQL Programming (6th ed.). O’Reilly Media.