Sub topic 7
Calling Subprograms from Blocks, Other Code, and Tools
This chapter assumes you can write an anonymous block and have created the procedures and functions from the earlier chapters: raise_salary, get_full_name, and get_salary_range. It covers the ways to invoke a stored subprogram, how each call context treats parameters and return values, and the errors you will meet most often.
Where calls come from
A stored subprogram does nothing until something calls it. The caller can be an anonymous block, another stored subprogram, a SQL statement (functions only), a command in a tool such as SQL*Plus or SQLcl, or an application using a driver.
Calling from an anonymous block
A procedure call is a complete statement. A function call is an expression, so its result must go somewhere: a variable, a condition, or another expression.
SET SERVEROUTPUT ON
DECLARE
v_name VARCHAR2(100);
v_min NUMBER;
v_max NUMBER;
BEGIN
raise_salary(100, 5); -- procedure: a statement
v_name := get_full_name(100); -- function: an expression
get_salary_range('IT_PROG', v_min, v_max); -- OUT parameters filled in
IF get_full_name(101) IS NULL THEN
DBMS_OUTPUT.PUT_LINE('No employee 101');
END IF;
DBMS_OUTPUT.PUT_LINE(v_name || ': ' || v_min || ' - ' || v_max);
END;
/Three rules follow from this example.
- A function call used as a statement fails to compile with
PLS-00221: 'GET_FULL_NAME' is not a procedure or is undefined. - An actual parameter for an
OUTorIN OUTformal parameter must be a variable. Passing a literal such asget_salary_range('IT_PROG', 0, 0)raisesPLS-00363: expression '0' cannot be used as an assignment target. - Positional and named notation work in every PL/SQL call, and you can mix them if the positional arguments come first.
raise_salary(100, p_percent => 5)is valid.raise_salary(p_employee_id => 100, 5)is not.
Calling from another subprogram
Calls inside stored code look the same as calls in an anonymous block. The difference is that the compiler records a dependency from the caller to the callee. If you later recompile the callee with a changed signature, the caller becomes INVALID and must be recompiled. The compilation chapter covers that in detail.
CREATE OR REPLACE PROCEDURE give_it_raise (
p_percent IN NUMBER DEFAULT 10
) AS
BEGIN
FOR r IN (SELECT employee_id
FROM employees
WHERE job_id = 'IT_PROG')
LOOP
raise_salary(r.employee_id, p_percent);
END LOOP;
END give_it_raise;
/Here raise_salary raises ORA-20001 if an employee is missing. The loop does not catch it, so the error propagates out of give_it_raise to its own caller. Handling it is a design choice, covered in the exception chapter.
The caller also owns the transaction. Neither raise_salary nor give_it_raise commits. When an exception ends a call from a client, Oracle undoes the changes that call made, and earlier work in the same transaction stays pending until you commit or roll back.
Calling from SQL*Plus and SQLcl
SQL*Plus and SQLcl are not PL/SQL engines. They have their own commands that wrap your call in an anonymous block.
SET SERVEROUTPUT ON
EXECUTE raise_salary(100, 5)
VARIABLE v_name VARCHAR2(100)
EXECUTE :v_name := get_full_name(100)
PRINT v_name
VARIABLE v_min NUMBER
VARIABLE v_max NUMBER
EXEC get_salary_range('IT_PROG', :v_min, :v_max)
PRINT v_min v_maxEXEC is the short form of EXECUTE. Both are client commands, not SQL, so they need no trailing semicolon and are not available in other tools. Internally the client sends BEGIN raise_salary(100, 5); END;. VARIABLE declares a client-side bind variable, which you reference with a colon prefix. PRINT displays it.
The SQL CALL statement
CALL is real SQL, so it works in any client that can run a SQL statement.
CALL raise_salary(100, 5);
VARIABLE v_name VARCHAR2(100)
CALL get_full_name(100) INTO :v_name;These restrictions apply to CALL:
- Parentheses are required, even when the subprogram has no parameters.
- A function call needs an
INTOclause that names a bind variable. - You cannot use
CALLwithOUTorIN OUTparameters in the same way as in a block. For those, use an anonymous block orEXEC.
For most work, an anonymous block is the most portable and predictable way to call a procedure. Use CALL when a tool accepts only a single SQL statement.
Calling functions from SQL
A stored function can appear wherever a SQL expression can: the select list, WHERE, ORDER BY, and so on.
SELECT employee_id, get_full_name(employee_id) AS full_name
FROM employees
WHERE department_id = 60;The function runs once for each row, and each call is a switch between the SQL engine and the PL/SQL engine. On large tables this context switching can dominate the run time, which is why the performance chapter introduces DETERMINISTIC and RESULT_CACHE. A function called from SQL also cannot use OUT or IN OUT parameters, and it should not change the database state. A function that issues DML fails with ORA-14551: cannot perform a DML operation inside a query. Procedures cannot be called in a query at all. SELECT raise_salary(100) FROM dual fails with ORA-06576: not a valid function or procedure name.
Calling from application code
Drivers expose stored subprograms through their own calling APIs. The example below uses python-oracledb and the same three subprograms.
import os
import oracledb
with oracledb.connect(
user=os.environ["DB_USER"],
password=os.environ["DB_PASSWORD"],
dsn=os.environ["DB_DSN"],
) as connection:
with connection.cursor() as cursor:
# Procedure with IN parameters
cursor.callproc("raise_salary", [100, 5])
# Function: give the Python return type, then the arguments
name = cursor.callfunc("get_full_name", str, [101])
print(name)
# OUT parameters: pass variable objects created by the cursor
lo = cursor.var(float)
hi = cursor.var(float)
cursor.callproc("get_salary_range", ["IT_PROG", lo, hi])
print(lo.getvalue(), hi.getvalue())
connection.commit()Other drivers follow the same shape. JDBC uses CallableStatement with {call raise_salary(?, ?)} and registerOutParameter for OUT values. The principles are the same everywhere: send values as bind variables instead of concatenating them into a string, declare the type of each output, and commit explicitly.
Finding the subprogram: names, schemas, and privileges
Oracle resolves an unqualified name in the calling schema first, then through synonyms. To call a subprogram in another schema, qualify it as hr.raise_salary(100, 5), or create a synonym for it. The caller also needs the EXECUTE privilege on it, either directly or through a role. Privileges received through a role do not apply inside definer's-rights stored code, which is why the next chapters treat grants and AUTHID together.
Common errors when calling
| Error | Typical cause |
|---|---|
| `PLS-00306: wrong number or types of arguments` | Too many or too few arguments, or a type mismatch. Also raised when no overload matches. |
| `PLS-00201: identifier must be declared` | Wrong name, wrong schema, or no `EXECUTE` privilege. |
| `PLS-00221: is not a procedure or is undefined` | A function called as a statement, or a procedure used in an expression. |
| `PLS-00363: expression cannot be used as an assignment target` | A literal passed for an `OUT` or `IN OUT` parameter. |
| `ORA-06576: not a valid function or procedure name` | A procedure in a `SELECT`, or `CALL` used with the wrong syntax. |
| `ORA-06550` | Wrapper error that points to the line and column of the real `PLS-` error that follows it. |
Exercise
In SQL*Plus, you want to call get_salary_range('SA_REP', ...) and display both values. Which commands declare the needed bind variables, make the call, and show the results?
Show answer
Declare two client variables with VARIABLE v_min NUMBER and VARIABLE v_max NUMBER. Call the procedure with EXEC get_salary_range('SA_REP', :v_min, :v_max). Show the results with PRINT v_min v_max. An anonymous block with local variables and DBMS_OUTPUT.PUT_LINE also works, as long as SET SERVEROUTPUT ON is active.
Exercise
SELECT raise_salary(100, 5) FROM dual; fails with ORA-06576, and BEGIN get_full_name(100); END; fails with PLS-00221. Why, and how do you fix each?
Show answer
A procedure returns no value, so it cannot appear in a query. Call it with EXEC raise_salary(100, 5) or in a block instead. A function returns a value, so a block must use it. Assign it to a variable (v_name := get_full_name(100);) or call it from SQL with SELECT get_full_name(100) FROM dual.