Create Procedure   «Prev  Next»

Lesson 4Calling procedures and functions
ObjectiveDescribe and demonstrate the capabilities and restrictions of calling procedures and functions from PL/SQL and from SQL expressions inside PL/SQL.

Calling Procedures and Functions in Oracle PL/SQL

A PL/SQL procedure can call another procedure or use a function's return value. A function can also call either kind of routine. These combinations let you separate a calculation from the operation that needs it: a pricing function can calculate an amount, while a procedure coordinates the work and passes the result to its caller.

The important question in Oracle AI Database 26ai is where the call occurs and what the complete call chain does. A function used in a SQL query follows SQL invocation rules even when that query appears inside a procedure. Calling an intermediate helper does not remove those rules. Ordinary procedural execution has a different context.

The previous lesson built the CALC_TOTAL procedure. Here, small independent examples make the calling relationships easier to follow before you combine them with table access. The examples show expected behavior; the displayed results are explanations, not records of execution against an Oracle instance.

Four calling relationships

Calling procedures and functions in PL/SQL
RelationshipNormal useWhat to check
Procedure calls functionUse the returned value in an assignment or expression.A function in an embedded SQL expression must satisfy SQL rules.
Procedure calls procedureInvoke a helper as a statement, with any required arguments.Check parameter modes, visibility, privileges, and transaction ownership.
Function calls functionUse another calculation's result to produce a return value.SQL restrictions follow the call chain when the outer function is SQL-invoked.
Function calls procedureInvoke a helper, possibly receiving values through OUT parameters.The helper's actions must fit the enclosing execution context.

A procedure invocation is a statement, such as quote_sale(100, 0.15, l_net);. A function invocation supplies a value, as in l_net := discounted_price(100, 0.15);. The function's result must be used in an appropriate expression; writing a standalone function call as though it were a procedure does not make the two interchangeable. See Oracle's subprogram invocation rules.

Think about the information each boundary carries. A caller supplies inputs; a function returns one value; a procedure can supply outputs through parameters. An exception is another possible outcome. Documenting only the successful return value leaves the caller without a policy for missing inputs or failed work. The examples below make these choices visible at the point where each helper is called.

A procedure calls a calculation function

This anonymous block declares a local function, discounted_price, followed by a local procedure, quote_sale. Both belong to the same enclosing block. The function does not have to be declared inside the procedure that calls it.

Run complete scripts in SQL*Plus or SQLcl, or use a compatible script mode in your Oracle client. SET SERVEROUTPUT ON enables display of buffered messages; it is a client command, not part of a stored routine. The final slash submits the completed PL/SQL block in these script clients.

SET SERVEROUTPUT ON

DECLARE
    l_net NUMBER;

    FUNCTION discounted_price (
        p_price IN NUMBER,
        p_rate  IN NUMBER
    ) RETURN NUMBER
    IS
    BEGIN
        IF p_price IS NULL OR p_rate IS NULL THEN
            RETURN NULL;
        END IF;
        IF p_price < 0 OR p_rate < 0 OR p_rate > 1 THEN
            RAISE VALUE_ERROR;
        END IF;
        RETURN ROUND(p_price * (1 - p_rate), 2);
    END discounted_price;

    PROCEDURE quote_sale (
        p_price IN  NUMBER,
        p_rate  IN  NUMBER,
        p_net   OUT NUMBER
    )
    IS
    BEGIN
        p_net := discounted_price(p_price, p_rate);
    END quote_sale;
BEGIN
    quote_sale(100, 0.15, l_net);
    DBMS_OUTPUT.PUT_LINE('Net amount: ' || l_net);
END;
/

Expected display:

Net amount: 85

The outer block calls quote_sale with a price of 100, a fractional discount rate of 0.15, and the writable variable l_net. The procedure passes the two inputs to discounted_price. That function calculates 100 multiplied by 0.85, rounds the result to two decimal places, and returns 85. Assignment to p_net sends the value back through the procedure's OUT parameter.

The rate is 0.15 for a 15 percent discount, not 15. The validation policy is also explicit: a NULL input produces NULL; otherwise, a negative price or a rate outside zero through one raises VALUE_ERROR. The NULL check runs first, so it takes precedence if the other input is invalid. This is a small teaching policy, not a complete specification for prices, refunds, or missing commercial data.

Although the function rounds to two decimal places, ordinary number-to-text conversion need not print trailing zeros. The result can therefore appear as 85 rather than 85.00. No SQL query or table update occurs in this calculation. The assignment within quote_sale invokes the function directly in PL/SQL.

To extend the example, an outer reporting procedure could call quote_sale and format the returned amount. That would add a procedure-to-procedure relationship without changing the discount formula. A second calculation function could similarly use discounted_price in an expression. Reuse should preserve the meaning of the rate and the agreed NULL policy across each additional call.

A function calls a procedure with an OUT parameter

The reverse relationship is equally useful to understand. Here a helper procedure supplies a value, and a function returns that value to its own caller. Descriptive names make the direction of the calls visible.

SET SERVEROUTPUT ON

DECLARE
    PROCEDURE set_demo_value (p_value OUT NUMBER)
    IS
    BEGIN
        p_value := 200;
    END set_demo_value;

    FUNCTION get_demo_value RETURN NUMBER
    IS
        l_value NUMBER;
    BEGIN
        set_demo_value(l_value);
        RETURN l_value;
    END get_demo_value;
BEGIN
    DBMS_OUTPUT.PUT_LINE(get_demo_value());
END;
/

Expected display:

200

get_demo_value passes its local variable to set_demo_value. The procedure assigns 200 through p_value; the function then returns its updated local value. Finally, PUT_LINE, a procedure in the DBMS_OUTPUT package, receives the number for display. Assigning a PL/SQL variable is not a database table modification.

OUT fits this helper because it supplies a new value without consuming the caller's previous value. An initial assignment of zero to l_value would add nothing to the successful path. Use IN OUT when the helper actually needs an existing value and then changes it. A variable containing NULL is a valid output destination; the literal NULL is not a writable destination.

These declarations last for the anonymous block's execution. They do not create standalone schema objects, and their names are not automatically available to arbitrary SQL queries. Review functions, procedures, and parameter modes if the difference between a return value and an output parameter is unfamiliar.

A SQL statement inside a procedure still follows SQL rules

Compare a direct assignment such as l_result := some_function(p_value); with SELECT some_function(p_value) INTO l_result FROM dual;. Both can occur in PL/SQL, but the second invokes the function through SQL. The containing procedure does not convert that query into an unrestricted procedural call.

For ordinary, nonautonomous execution, Oracle applies these restrictions to the SQL-invoked function and the routines it calls:

  • A function invoked by SELECT cannot modify database tables. The same restriction applies when invoked by parallel DML.
  • When DML invokes a function, the function cannot query or modify tables changed by that statement. Oracle documents a narrow mutating-table exception for a single-row INSERT ... VALUES outside FORALL.
  • SQL invocation restricts transaction control, session control, system control, and DDL. Moving a restricted statement into a helper does not bypass the restriction.

Oracle documents autonomous-transaction qualifications, but these introduce separate transaction behavior. They are not a default solution for a calculation function. See functions that SQL statements can invoke.

A function exposed to SQL also needs a suitable SQL interface, including IN formal parameters and SQL-compatible types. This requirement concerns the SQL-facing function. Its internal helper procedure can still use an OUT parameter to assign a local variable, as the preceding example demonstrates. Oracle's guide to subprograms and packages describes these interface restrictions.

Oracle 26ai SQL can use a BOOLEAN-returning function

Oracle 26ai supports SQL BOOLEAN, including TRUE, FALSE, and NULL, which represents an unknown logical value. SQL BOOLEAN support was already available in Oracle 23ai. Advice that excludes every Boolean-returning function from SQL belongs to older releases such as Oracle 19c, where a SQL-facing wrapper needs a supported representation such as a number or string. See the 26ai SQL data types and Oracle's 23ai SQL examples.

The following example creates a standalone function so that SQL can resolve its name. Use an Oracle 26ai practice schema with the required CREATE PROCEDURE privilege. CREATE OR REPLACE FUNCTION is DDL and can commit pending work; the first two anonymous blocks did not create stored objects. Oracle documents these requirements under CREATE FUNCTION.

CREATE OR REPLACE FUNCTION lesson4_is_positive (
    p_value IN NUMBER
) RETURN BOOLEAN
IS
BEGIN
    RETURN p_value > 0;
END lesson4_is_positive;
/
SHOW ERRORS FUNCTION lesson4_is_positive

SELECT lesson4_is_positive(10)   AS positive_value,
       lesson4_is_positive(0)    AS zero_value,
       lesson4_is_positive(NULL) AS unknown_value
FROM dual;

Expected query values: positive_value is TRUE, zero_value is FALSE, and unknown_value is NULL. The client might display NULL as an empty cell. It must not be interpreted as FALSE. The function simply returns the comparison result and needs no DETERMINISTIC clause for this ordinary query.

Keep creation and invocation separate when diagnosing this script. First inspect the function's compilation diagnostics with SHOW ERRORS. Then examine the three query columns. A stored definition, a successful query, and correct results are different checkpoints. If you change the comparison to include zero, the expected zero result must change too; the caller's messages should continue to describe the revised rule accurately.

After creating that function, the next block calls it through a query inside a local procedure. Explicit branches translate all three logical outcomes into text.

SET SERVEROUTPUT ON

DECLARE
    PROCEDURE report_sign (p_value IN NUMBER)
    IS
        l_positive BOOLEAN;
    BEGIN
        SELECT lesson4_is_positive(p_value)
        INTO l_positive
        FROM dual;

        IF l_positive IS NULL THEN
            DBMS_OUTPUT.PUT_LINE('UNKNOWN');
        ELSIF l_positive THEN
            DBMS_OUTPUT.PUT_LINE('POSITIVE');
        ELSE
            DBMS_OUTPUT.PUT_LINE('NONPOSITIVE');
        END IF;
    END report_sign;
BEGIN
    report_sign(10);
    report_sign(0);
    report_sign(NULL);
END;
/

Expected display:

POSITIVE
NONPOSITIVE
UNKNOWN

The NULL branch comes first so that an unknown comparison receives its own message. Zero is nonpositive, as is a negative number. This code prints text literals instead of depending on implicit conversion of a Boolean value to text or a particular PLSQL_IMPLICIT_CONVERSION_BOOL setting. The SELECT inside report_sign remains a SQL invocation; a direct assignment would demonstrate a different context. The earlier lesson on Boolean-returning functions provides further practice with NULL policy.

DETERMINISTIC describes a promise, not permission

An ordinary SQL call does not universally require DETERMINISTIC. The clause asserts that a function obeys specific rules, including returning the same result for the same inputs and having no side effects. Oracle requires it for particular uses, such as functions in function-based indexes. It does not authorize restricted DML or transaction control.

Do not add the clause just to make code appear faster or more compatible. Results that depend on changing table data or session state can invalidate the promise, and Oracle may not diagnose the incorrect assertion. The examples here omit it deliberately. Consult the DETERMINISTIC clause reference before using it.

Visibility and privileges determine which helper you can call

In the first block, discounted_price is declared before quote_sale. In the second, set_demo_value appears before get_demo_value. This order makes each helper visible when its caller is compiled. When declaration order cannot express the relationship, PL/SQL supports a matching forward declaration.

For shared stored code, a package specification exposes public routines, while its body can contain private helpers. A name declared only in an unrelated anonymous block is not a reusable external interface. Packages provide an organizational boundary; simply moving these examples into a package would not establish a performance improvement. See nested, packaged, and standalone subprograms.

A schema prefix identifies an object but does not grant permission to execute it. Cross-schema calls need the appropriate privileges, and stored units have compilation and runtime privilege rules. AUTHID DEFINER and AUTHID CURRENT_USER affect runtime name resolution and privilege checking. Avoid assuming that every routine always runs with its caller's rights; review Oracle's AUTHID documentation when designing the interface.

Keep transaction ownership and error handling explicit

Ordinary nonautonomous calls share the active transaction. A helper's COMMIT can commit work performed earlier by its caller, not just work inside that helper. Choose a clear transaction owner so callers know whether they can still roll back the complete business operation. Two ordinary routines updating the same row in the same transaction do not inherently deadlock; conflicts between transactions are a different situation. Oracle describes transaction completion under COMMIT.

An autonomous routine has an independent transaction. Its committed changes survive rollback of the main transaction, and it can deadlock if it waits for resources held by its suspended caller. These consequences explain why autonomy should be a deliberate design decision, not a convenient way to hide work inside a query. See autonomous transactions.

A helper exception can propagate through a function to its caller. You do not need a handler at every level. In the discount example, an invalid rate raises VALUE_ERROR; returning zero instead would change a failed calculation into an apparently valid price. Handle an exception where meaningful recovery or translation is possible, and avoid silently discarding failures with WHEN OTHERS THEN NULL. Oracle explains this behavior in exception propagation.

For SQL-facing functions, prefer calculations whose results do not depend on how many times the query invokes them. SQL does not promise the call count or evaluation order that a procedural loop suggests. Keep operations requiring a particular sequence in explicit procedural code, and measure performance before making claims about nesting or packaging.

Check the calling contract before combining routines

Trace one successful input and one boundary case through each parameter and return value. For quote_sale, 100 and 0.15 produce 85; a missing input produces NULL; a rate of 1.5 raises an exception. For get_demo_value, the helper supplies 200. For the Boolean example, 10, zero, and NULL take three different logical paths. Compilation alone would not verify these outcomes.

When trying the scripts in a practice database, run the first two blocks independently. For the Boolean demonstration, create the stored function before running report_sign, and keep both in a session that can resolve that function. If output is missing, check the client's output setting separately from the calculation. If compilation fails, inspect the diagnostic and declaration scope before changing business logic.

During review, distinguish an incorrect result from an intentionally raised exception. A failed validation should not be recorded as a successful discount calculation. Likewise, an unknown sign is an expected outcome for NULL input, not evidence that the helper failed. Recording inputs together with expected values or exceptions gives a future maintainer a precise basis for checking changes.

Then identify the invocation context, check what every helper does, and confirm visibility, privileges, and transaction ownership. These checks make the calling relationship useful without turning a short routine into a source of hidden effects. The next lesson develops this design by adding a function to a procedure.

Oracle PL/SQL Programming: Additional reading on organizing PL/SQL programs.

SEMrush Software 4 SEMrush Banner 4