


Oracle PL/SQL Functions
Oracle Tips by Burleson

The most common use of functions is to hold both simple and complex
mathematical equations that are performed frequently by an
application, but other simple tasks can also be accomplished.
Welldesigned functions, like welldesigned procedures, are coded to
perform one task. Like procedures, functions can accept and return
values to calling objects via parameters, but returning values from a
function via parameters is typically viewed as a poor coding practice.
Listing 1.10 presents a typical stored function.
Listing 1.10 A typical stored function.
FUNCTION Calculate_GPA (nSSN IN integer)
RETURN NUMBER
IS
nOverallGPA number := 0;
iSumCredits integer := 0;
iTotalHours integer := 0;
iLogicStep integer := 0;
BEGIN
SELECT sum (credit_hours),
sum (decode (course_grade,
'A', 4,
'B', 3,
'C', 2,
'D', 1, 0))
INTO iTotalHours,
iSumCredits
FROM ENROLLED_COURSES
WHERE ssn = nSSN;
iLogicStep := 1;
nOverAllGPA := iSumCredits / iTotalHours;
iLogicStep := 2;
RETURN nOverAllGPA;
EXCEPTION
WHEN OTHERS THEN
SYSTEM_LOG.Log_Error (obj_name => 'Calculate_GPA',
obj_step => iLogicStep,
ora_error => substr (SQLERRM, 1, 65));
END Calculate_GPA;
This function closely resembles the procedural implementation of
Calculate_GPA( ), but the function does have one advantage that the
procedure doesn’t—the function can be called inside an SQL statement,
as shown in Listing 1.11.
Listing 1.11 Use of the Calculate_GPA() function in
an SQL statement.
UPDATE STUDENTS
SET overall_gpa = Calculate_GPA (nSSN => ssn);
This is an excerpt from the book "High
Performance Oracle Database Automation" by
Jonathan Ingram and Donald K. Burleson, Series Editor.
