Sub topic 5
Passing Data In and Out with IN, OUT, and IN OUT
This chapter covers how each parameter mode moves data between a caller and a subprogram. It assumes you can write anonymous blocks, you know the difference between a procedure and a function, and you have created a simple stored procedure with CREATE OR REPLACE. The examples use the employees table from the Oracle HR sample schema.
What a parameter mode controls
A parameter mode states which direction data may travel and what the subprogram is allowed to do with the parameter. You write the mode after the parameter name. If you omit it, Oracle uses IN.
| Mode | Value arrives from caller | Subprogram may assign to it | Value returned to caller | Actual parameter must be |
|---|---|---|---|---|
| `IN` | Yes | No | No | Any expression, including a literal |
| `OUT` | No (starts as NULL) | Yes | Yes, on normal completion | A variable |
| `IN OUT` | Yes | Yes | Yes, on normal completion | A variable |
The terms "formal parameter" and "actual parameter" matter here. The formal parameter is the name declared in the subprogram header. The actual parameter is the value or variable the caller supplies.
IN: read-only input
IN is the default, and it is the right choice for most parameters. Inside the subprogram, an IN parameter behaves like a constant. Assigning to it causes a compilation error (PLS-00363).
CREATE OR REPLACE PROCEDURE raise_salary (
p_employee_id IN employees.employee_id%TYPE,
p_percent IN NUMBER DEFAULT 10
) AS
BEGIN
UPDATE employees
SET salary = salary * (1 + p_percent / 100)
WHERE employee_id = p_employee_id;
IF SQL%ROWCOUNT = 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'Employee not found: ' || p_employee_id);
END IF;
END raise_salary;
/Because an IN actual parameter can be any expression, raise_salary(100, 2 * 5) is valid. Only IN parameters can have a DEFAULT value. The next chapter covers defaults and call notation.
OUT: returning extra values
An OUT parameter lets a procedure hand values back to the caller. The classic use is returning more than one value, which a function's single RETURN cannot do.
CREATE OR REPLACE PROCEDURE get_salary_range (
p_job_id IN employees.job_id%TYPE,
p_min OUT NUMBER,
p_max OUT NUMBER
) AS
BEGIN
SELECT MIN(salary), MAX(salary)
INTO p_min, p_max
FROM employees
WHERE job_id = p_job_id;
END get_salary_range;
/
DECLARE
v_min NUMBER;
v_max NUMBER;
BEGIN
get_salary_range('IT_PROG', v_min, v_max);
DBMS_OUTPUT.PUT_LINE('Range: ' || v_min || ' - ' || v_max);
END;
/Three behaviors of OUT parameters often surprise people.
- The incoming value is discarded. On entry, an
OUTparameter is initialized to NULL, whatever the caller's variable held. A scalarOUTparameter has no usable input value. - The actual parameter must be a variable. Calling
get_salary_range('IT_PROG', 5, 10)fails to compile, because a literal cannot receive a value. - If the subprogram never assigns the parameter, the caller gets NULL back. Oracle does not warn you. An
IFbranch that skips the assignment is a common cause.
You can read an OUT parameter after you assign it, for example p_min := p_min + 1 after the SELECT. This is allowed in PL/SQL, although it does not work in some other languages.
IN OUT: modify in place
An IN OUT parameter brings a value in and sends the changed value back. Use it when the subprogram transforms something the caller already holds.
CREATE OR REPLACE PROCEDURE normalize_text (
p_text IN OUT VARCHAR2
) AS
BEGIN
p_text := UPPER(TRIM(p_text));
END normalize_text;
/
DECLARE
v_text VARCHAR2(50) := ' hello world ';
BEGIN
normalize_text(v_text);
DBMS_OUTPUT.PUT_LINE('[' || v_text || ']');
END;
/The output is [HELLO WORLD]. If the caller passes a NULL variable, the subprogram sees NULL, so a transformation that assumes a value should check for it.
Constraints on formal parameters
A formal parameter declaration cannot carry a size, precision, or scale. You write p_text IN OUT VARCHAR2, not VARCHAR2(50), and p_min OUT NUMBER, not NUMBER(8,2). The constraint comes from the actual parameter.
For VARCHAR2, this has a practical consequence. An OUT parameter takes its maximum length from the caller's variable. If the procedure assigns a 40-character string to a caller variable declared as VARCHAR2(10), the call raises ORA-06502: PL/SQL: numeric or value error: character string buffer too small. The error appears at the call site or on return, not at compile time.
To avoid mismatches, anchor the type to a column with %TYPE, as raise_salary does with employees.employee_id%TYPE. A %TYPE anchor in a parameter inherits the data type of the column, but not its NOT NULL constraint. Use anchored declarations in the caller as well so both sides follow the column definition.
What happens when an exception occurs
By default, Oracle passes OUT and IN OUT parameters by value. It works on a temporary copy inside the subprogram and copies the result back to the caller's variable only if the subprogram finishes normally. If an unhandled exception propagates out, the caller's variable keeps its previous value.
CREATE OR REPLACE PROCEDURE fail_after_assign (
p_value OUT NUMBER
) AS
BEGIN
p_value := 1;
RAISE_APPLICATION_ERROR(-20002, 'Simulated failure');
END fail_after_assign;
/
DECLARE
v_result NUMBER := 99;
BEGIN
fail_after_assign(v_result);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
DBMS_OUTPUT.PUT_LINE('v_result = ' || v_result);
END;
/The handler prints v_result = 99, not 1. The assignment inside the procedure was never copied back. Do not rely on OUT values after a failed call.
The NOCOPY hint asks Oracle to pass by reference instead. With NOCOPY, the value in the caller's variable may already be changed when the exception occurs, so the result becomes unpredictable. A later chapter covers NOCOPY and when it is worth that risk.
Choosing between OUT parameters and a function
Both can return data, so the choice affects how readable the call is.
- Use a function when the result is one value and the call reads naturally as an expression. Functions can also be called from SQL.
- Use a procedure with OUT parameters when you need several values at once, or when the call also performs an action such as DML.
- Avoid
OUTandIN OUTparameters on functions. A function with such a parameter cannot be called from a SQL statement, and the side effect on the caller's variable makes expressions harder to reason about. - Avoid
IN OUTwhenINplus a returned value would be clearer. AnIN OUTparameter makes the reader check both what goes in and what comes out.
Common errors
| Symptom | Likely cause |
|---|---|
| PLS-00363: expression cannot be used as an assignment target | Assigning to an `IN` parameter, or passing a literal as an `OUT` argument |
| `OUT` value is NULL after the call | The subprogram never assigned it on that code path |
| ORA-06502 on return | The caller's `VARCHAR2` variable is shorter than the value assigned |
| Caller's variable unchanged after an error | By-value copy-back did not happen because of the unhandled exception |
Exercise
A procedure declared with p_total OUT NUMBER is called as calc(v_total), where v_total was set to 500 before the call. The procedure body contains only NULL;. What does v_total hold afterward, and why?
Show answer
It holds NULL. An OUT parameter is initialized to NULL on entry and the incoming value of 500 is discarded. Because the procedure never assigns ptotal, the NULL is copied back to vtotal when the call completes normally.
Exercise
You need a routine that takes an employee ID and returns both the full name and the hire date. Would you write a function or a procedure, and which parameter modes would you use?
Show answer
Write a procedure. It needs two returned values, which a single function RETURN cannot supply. Use p_employee_id IN employees.employee_id%TYPE, then p_name OUT VARCHAR2 and p_hire_date OUT DATE. A caller declares two variables and passes them in the second and third positions.