Learning Objectives – after this chapter you will be able to:
  • 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.

AdvantageWhy
Reduced network trafficThe client sends only the procedure name, not the whole block.
Better performanceStored 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 maintenanceBusiness logic is changed once in the procedure; all clients use the new version – improving integrity and consistency.
SecurityUsers get EXECUTE on the procedure but no access to the underlying tables; the procedure runs with the owner’s privileges.
CREATE [OR REPLACE] PROCEDURE name [(parameter, ...)] {IS | AS} [local declarations] BEGIN executable statements [EXCEPTION exception handlers] END [name]; CREATE [OR REPLACE] FUNCTION name [(parameter, ...)] RETURN datatype {IS | AS} ... BEGIN ... RETURN value; END [name];
A procedure and a function
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.
ModeBehaviourActual parameter
IN (default)Passes a value in; acts like a constant – cannot be assignedVariable, constant or expression
OUTReturns a value to the caller; uninitialised inside the subprogramMust be a variable
IN OUTReceives a value and returns a valueMust be a variable
OUT parameters
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;
Output
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 – defaultInvoker rights – AUTHID CURRENT_USER (Oracle8i)
Privileges usedOwner’sCalling user’s
Unqualified objects resolve toOwner’s schema (SRIKANTH.MESSAGES)Invoker’s schema (PRANEETH.MESSAGES – ORA-00942 if missing)
BenefitUsers need only EXECUTE; tables stay protectedCentralised 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.
COURSE_PKG
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);
Key Takeaways
  • 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)
ch19.pdf 17 pages 369 KB Open in PDF Viewer (Free Tool)

Your browser cannot show this PDF here. Open Chapter 19 Notes (PDF)

ch19.pdfKeys: ← → page · + − zoom · F full screen
Question / Answer (15 questions)

Moderate-level questions based on the Chapter 19 notes (PDF). Click a question to see the answer.

Answer : A stored procedure is a PL/SQL block stored in the database as an object with a name and invoked using that name; it is also called a database procedure and may take parameters. A function is similar to a procedure except that it returns a value, which the calling program uses.

Answer : Reduced network traffic (only the name is sent to the server), better performance (stored in compiled form in the database and shared in server memory), easy maintenance (business logic changed once in the procedure is used by all clients) and security (users can execute the procedure without having privileges on the underlying tables).

Answer : The procedure and the data it accesses are both in the database, and because its compiled form is stored, no compilation step is required to execute it. It also uses shared memory – once brought into server memory by one user, another user may find it already in memory.

Answer : Oracle creates a procedure even when it has errors and displays "Warning: Procedure created with compilation errors". SHOW ERRORS displays the errors of the most recent CREATE PROCEDURE. OR REPLACE lets the corrected version replace the existing (invalid) procedure; without it Oracle does not allow an existing procedure to be replaced.

Answer : With the EXECUTE command, e.g. EXECUTE newpayment(10, 2000). The user must be the owner of the procedure or must have the EXECUTE privilege on it.

Answer : RETURN datatype in the header specifies the type of value returned. The RETURN statement in the executable part returns the value, which must be of the same type, e.g. RETURN v_fee - v_amtpaid in GETDUEAMT. User-defined functions can be used in SQL like standard functions, e.g. SELECT rollno, getdueamt(rollno) FROM students.

Answer : The USER_SOURCE data dictionary view holds the source, e.g. SELECT text FROM user_source WHERE name = 'NEWPAYMENT'. To create a procedure you need the CREATE PROCEDURE system privilege and the object privileges on the objects it refers to; the owner cannot obtain these required privileges through roles.

Answer : Procedures are stored in compiled form; if a procedure becomes invalid (e.g. it referred to a table without privilege, and the privilege is granted later) it must be recompiled before execution. Oracle recompiles it implicitly when referred, but to avoid the run-time delay it can be recompiled explicitly with ALTER PROCEDURE name COMPILE or ALTER FUNCTION name COMPILE. USER_OBJECTS shows the status (VALID/INVALID).

Answer : Formal parameters are declared in the definition of the procedure and receive the values sent while calling it, e.g. pccode and pamt in increase_fee(pccode varchar2, pamt number). Actual parameters are the values given within parentheses while calling, e.g. v_ccode and 2000; they are copied to the corresponding formal parameters.

Answer : IN (the default) passes a value to the subprogram; it acts like a constant and cannot be assigned; the actual parameter can be a variable, constant or expression. OUT lets the subprogram pass a value back to the caller; it is uninitialised inside the subprogram and the actual parameter must be a variable. IN OUT both receives a value and returns a value; its actual parameter must also be a variable.

Answer : By default OUT and IN OUT parameters are passed by value – copied into the formal parameter and copied back on normal exit. For large data structures such as records and object instances this copying slows execution and uses more memory, so NOCOPY lets PL/SQL pass OUT and IN OUT parameters by reference, e.g. pstudent IN OUT NOCOPY student_type.

Answer : With definer (owner) rights – the default – a procedure runs with the privileges of its owner and all unqualified object references resolve to the owner’s schema. With invoker rights, introduced in Oracle8i and specified with AUTHID CURRENT_USER, it runs with the privileges of the calling user and unqualified objects resolve to the invoker’s schema, allowing centralised code with data stored in each user’s schema.

Answer : It creates your own application error number and message: RAISE_APPLICATION_ERROR(errornumber, errormessage). It terminates the PL/SQL program and sends the error code and message to the host environment, e.g. RAISE_APPLICATION_ERROR(-20100, 'Invalid course code'). The error number is a negative number in the -20000 range (the notes give -20001 to -20999).

Answer : A package is a collection of related procedures, functions, variables and datatypes. The specification (CREATE PACKAGE) declares the public items, which are visible and callable outside the package as package_name.object_name. The body (CREATE PACKAGE BODY) defines the public procedures, functions and cursors and also private procedures, functions and variables that are used only inside the package.

Answer : The initialisation part is a BEGIN ... section at the end of the package body containing code executed when a user refers to the package for the first time. Packages group related procedures and functions under one name and avoid name conflicts between procedures.
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.

Q1. Which command displays the errors that occurred while compiling a stored procedure?

Show Answer

Correct Answer : D. SHOW ERRORS
SHOW ERRORS displays the compilation errors of the most recent CREATE PROCEDURE/FUNCTION.

Q2. Which data dictionary view provides the source code of stored procedures?

Show Answer

Correct Answer : A. USER_SOURCE
USER_SOURCE contains the text of stored procedures and functions.

Q3. Which parameter mode specifies that a parameter is both input and output?

Show Answer

Correct Answer : B. IN OUT
IN OUT receives a value from the caller and returns a value to it.

Q4. Which command explicitly recompiles a procedure?

Show Answer

Correct Answer : C. ALTER PROCEDURE p COMPILE
ALTER PROCEDURE name COMPILE (ALTER FUNCTION for functions) recompiles explicitly.

Q5. Which option makes a procedure run with the privileges of the calling user?

Show Answer

Correct Answer : D. AUTHID CURRENT_USER
AUTHID CURRENT_USER gives invoker rights; definer rights are the default.

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.

  1. Srikanth, P. (n.d.). Oracle For Beginners (chapter notes – the PDF shown on each chapter page). Srikanth Technologies. http://www.srikanthtechnologies.com/
  2. Oracle Corporation. (n.d.). Oracle Database PL/SQL Language Reference, 19c. https://docs.oracle.com/en/database/oracle/oracle-database/19/lnpls/
  3. Oracle Corporation. (n.d.). Oracle Database Development Guide, 19c. https://docs.oracle.com/en/database/oracle/oracle-database/19/adfns/
  4. Oracle Corporation. (n.d.). Oracle Database Security Guide, 19c. https://docs.oracle.com/en/database/oracle/oracle-database/19/dbseg/
  5. Feuerstein, S., & Pribyl, B. (2014). Oracle PL/SQL Programming (6th ed.). O’Reilly Media.