Sub topic 5
Passing Data In and Out with IN, OUT, and IN OUT
Assume you know basic SQL and anonymous PL/SQL blocks. You should also know how to declare variables with DECLARE, run statements in BEGIN, and handle errors with EXCEPTION.
A parameter is a named value that a subprogram receives or returns. Its mode controls how data moves between the caller and the procedure or function.
| Mode | Data enters the subprogram | Data returns to the caller | Typical use |
|---|---|---|---|
| `IN` | Yes | No | Input such as an employee ID |
| `OUT` | No | Yes | A calculated result or status |
| `IN OUT` | Yes | Yes | Updating a value supplied by the caller |
The `IN` mode
IN is the default parameter mode. The caller supplies a value, and the subprogram can read it but cannot assign a new value to the formal parameter.
CREATE OR REPLACE PROCEDURE show_employee (
p_employee_id IN employees.employee_id%TYPE
) AS
v_name employees.first_name%TYPE;
BEGIN
SELECT first_name
INTO v_name
FROM employees
WHERE employee_id = p_employee_id;
DBMS_OUTPUT.PUT_LINE('Employee: ' || v_name);
END show_employee;
/The %TYPE attribute anchors p_employee_id to the type of the employee_id column. If that column's type changes, the parameter follows it when the procedure is recompiled.
The `OUT` mode
OUT returns a value through a variable supplied by the caller. The procedure should assign the parameter before it finishes normally. Treat an OUT parameter as having no usable input value when the procedure starts.
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;
/The caller must provide variables for OUT parameters. A literal such as 100 cannot receive a result.
The `IN OUT` mode
IN OUT passes an initial value into the subprogram and returns the changed value. This mode is useful when a procedure transforms a caller's variable.
CREATE OR REPLACE PROCEDURE add_tax (
p_amount IN OUT NUMBER,
p_rate IN NUMBER
) AS
BEGIN
p_amount := p_amount * (1 + p_rate);
END add_tax;
/
DECLARE
v_amount NUMBER := 100;
BEGIN
add_tax(v_amount, 0.20);
DBMS_OUTPUT.PUT_LINE('After tax: ' || v_amount);
END;
/The procedure reads 100, changes the formal parameter to 120, and copies that result back into v_amount.
Exercise
Which parameter mode should a procedure use to receive a starting counter value, increase it, and return the new counter value?
Show answer
Use IN OUT because the procedure must read the starting value and return the changed value.