Sub topic 4
Creating a Stored Function and Returning a Value
This chapter covers how to create a stored function in Oracle PL/SQL, how it returns a value, and the mistakes that most often break it. It assumes you know basic SQL (SELECT, INSERT, UPDATE, DELETE), can write an anonymous block with DECLARE, BEGIN, EXCEPTION and END, know the common Oracle data types (NUMBER, VARCHAR2, DATE), and have an Oracle schema with the CREATE PROCEDURE privilege. That privilege also covers creating functions.
What a stored function is
A stored function is a named PL/SQL subprogram that is saved in the database and always returns exactly one value. The caller uses that value inside an expression. A procedure, by contrast, is called as a statement and returns nothing through its own name.
Use a function when the result is a single value that the caller will assign, compare, or print. Use a procedure when the goal is an action, such as updating rows.
Syntax
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN] datatype [DEFAULT value], ...)]
RETURN return_datatype
[AUTHID DEFINER | CURRENT_USER]
[DETERMINISTIC]
{IS | AS}
-- declarations
BEGIN
-- executable statements, ending in RETURN
[EXCEPTION
-- handlers]
END [function_name];
/Three details matter here.
- The keyword is RETURN in the header and RETURN in the body. In the header it names the data type. In the body it gives a value.
- You write the data type without a length or precision. Write
RETURN VARCHAR2, notRETURN VARCHAR2(100). The same rule applies to parameter types. - IS and AS mean the same thing here.
CREATE OR REPLACE creates the function if it is new. If a function with that name already exists in your schema, it replaces it and keeps existing grants. Plain CREATE fails with ORA-00955 when the name is already in use.
A first function
This function builds an employee's full name from the key.
CREATE OR REPLACE FUNCTION get_full_name (
p_employee_id IN employees.employee_id%TYPE
) RETURN VARCHAR2 AS
v_name VARCHAR2(100);
BEGIN
SELECT first_name || ' ' || last_name
INTO v_name
FROM employees
WHERE employee_id = p_employee_id;
RETURN v_name;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN NULL;
END get_full_name;
/Reading it from the top:
p_employee_id IN employees.employee_id%TYPEis an anchored parameter.%TYPEcopies the column's data type, so the function keeps working if the column definition changes.RETURN VARCHAR2declares the type of the value the function hands back.v_name VARCHAR2(100)is a local variable. Local variables, unlike the header, need a length.SELECT ... INTOloads one row into the variable. It raises NODATAFOUND for zero rows and TOOMANYROWS for more than one.RETURN v_nameends execution and sends the value to the caller.- The exception handler returns NULL when the employee does not exist. This is a design choice, discussed below.
The trailing / on its own line tells SQL*Plus, SQLcl, and SQL Developer scripts to send the block to the database. Without it, the tool waits for more input.
How RETURN works
A RETURN statement stops the function immediately and passes its expression to the caller. The expression must be compatible with the declared return type, and Oracle converts it implicitly where it can.
A function may contain several RETURN statements, for example in the branches of an IF. Every path through the function must end in a RETURN or in a raised exception. If execution reaches the final END without either, Oracle raises ORA-06503: PL/SQL: Function returned without value. The compiler cannot always detect this, so the error appears at run time.
CREATE OR REPLACE FUNCTION grade_label (
p_score IN NUMBER
) RETURN VARCHAR2 AS
BEGIN
IF p_score >= 90 THEN
RETURN 'A';
ELSIF p_score >= 75 THEN
RETURN 'B';
ELSIF p_score >= 0 THEN
RETURN 'C';
END IF;
RETURN NULL; -- covers negative and NULL scores
END grade_label;
/Without the last RETURN NULL, a call with a negative or NULL score would fall off the end and raise ORA-06503.
Calling the function
Because a function produces a value, you call it where an expression is allowed.
DECLARE
v_name VARCHAR2(100);
BEGIN
v_name := get_full_name(100);
DBMS_OUTPUT.PUT_LINE('Employee: ' || NVL(v_name, '(not found)'));
END;
/You can also call it in SQL, which later chapters cover in detail:
SELECT employee_id, get_full_name(employee_id) AS full_name
FROM employees
WHERE department_id = 60;Calling a function as a bare statement, as in get_full_name(100);, is a compile error (PLS-00221 or PLS-00306 depending on context). The value has nowhere to go.
The flow of a call
Choosing what to do when there is no result
The get_full_name function turns a missing row into NULL. That is not the only option, and the choice affects every caller.
| Approach | Behavior | Good when |
|---|---|---|
| Return NULL | Caller must test for NULL | A missing value is a normal outcome, and the function is used in SQL |
| Let NO_DATA_FOUND propagate | Caller gets an exception | A missing row means a bug or a bad key |
| Raise a custom error with RAISE_APPLICATION_ERROR | Caller gets a named, documented error | The business rule needs a clear message |
Pick one convention per codebase and document it. A subtle trap: when a function with an unhandled NODATAFOUND is called from a SQL statement, the exception can be silently treated as "no data" in some contexts, which hides the problem. Returning NULL explicitly or raising a custom error avoids that ambiguity.
Parameters in functions
Function parameters follow the same rules as procedure parameters. They can be IN, OUT, or IN OUT, and can have defaults.
CREATE OR REPLACE FUNCTION add_tax (
p_amount IN NUMBER,
p_rate IN NUMBER DEFAULT 0.2
) RETURN NUMBER AS
BEGIN
RETURN ROUND(p_amount * (1 + p_rate), 2);
END add_tax;
/Two calls show defaults in action:
BEGIN
DBMS_OUTPUT.PUT_LINE(add_tax(100)); -- uses 0.2, prints 120
DBMS_OUTPUT.PUT_LINE(add_tax(100, 0.07)); -- prints 107
END;
/Although OUT and IN OUT parameters are legal in functions, avoid them in functions you plan to call from SQL. Oracle does not allow a function with OUT or IN OUT parameters to be called from a SQL statement. If you need to return several values, a procedure with OUT parameters is usually the clearer choice. Another option is to return a record or a collection.
Functions that modify data
A function may run INSERT, UPDATE, or DELETE statements. That is legal when you call it from PL/SQL. It is not legal when a query or DML statement calls it: Oracle raises ORA-14551 (cannot perform a DML operation inside a query) in a SELECT, and ORA-04091 (mutating table) when the function reads or writes the table being changed by the calling statement. Keep functions that you intend to use in SQL free of side effects.
Checking that it compiled
CREATE OR REPLACE can succeed with compile errors. SQL*Plus then prints "Warning: Function created with compilation errors." The object is stored but marked INVALID. To see the errors:
SELECT line, position, text
FROM user_errors
WHERE name = 'GET_FULL_NAME'
AND type = 'FUNCTION'
ORDER BY sequence;In SQL*Plus and SQLcl, SHOW ERRORS gives the same information for the last object you compiled. Names in the data dictionary are stored in uppercase unless you created them with quoted identifiers.
Common errors
- Length in the RETURN type.
RETURN VARCHAR2(50)fails with a syntax error (PLS-00103). - Missing RETURN on a path. Compiles, then fails with ORA-06503 at run time.
- Wrong type returned. Returning a value that cannot convert to the declared type raises ORA-06502 (numeric or value error).
- Variable too small. Putting a 150-character string into
v_name VARCHAR2(100)raises ORA-06502. - Missing slash. The script appears to hang because the tool is waiting for the terminator.
- Calling as a statement. Assign the result, or use it in an expression.
Exercise
Write a function is_manager(p_employee_id) that returns 'Y' when at least one employee has that person as managerid, and 'N' otherwise. Which statement guarantees the function never raises NODATA_FOUND, and why is that simpler than catching the exception?
Show answer
Use COUNT(), which always returns exactly one row. CREATE OR REPLACE FUNCTION ismanager ( pemployeeid IN employees.employeeid%TYPE ) RETURN VARCHAR2 AS v_count NUMBER; BEGIN SELECT COUNT() INTO vcount FROM employees WHERE managerid = pemployeeid; RETURN CASE WHEN vcount > 0 THEN 'Y' ELSE 'N' END; END ismanager; / An aggregate query without GROUP BY returns one row even when no rows match, so neither NODATAFOUND nor TOOMANYROWS can occur and no handler is needed.
Exercise
A function has an IF branch that returns 'HIGH' when pvalue > 100 and an ELSIF branch that returns 'LOW' when pvalue < 10. It compiles without errors. What happens when you call it with 50, and how do you fix it?
Show answer
Execution reaches the final END without a RETURN, so Oracle raises ORA-06503 (Function returned without value) at run time. Fix it by adding an ELSE branch or a final RETURN statement, for example RETURN 'MEDIUM', so every path ends in a RETURN or a raised exception.