Sub topic 9
Cursors with Parameters
A cursor with parameters is an explicit cursor whose query takes input values when it is opened. This chapter assumes you can write an anonymous PL/SQL block, declare and open an explicit cursor, and loop over it with FETCH or a cursor FOR loop. It also assumes you know basic exception handling.
Why parameters
Suppose you need the same employee query for department 50 and then for department 60. You could declare two cursors that differ only in a literal. You could also declare one cursor that reads a package variable, but then the query depends on hidden state. A cursor parameter is the cleaner option. The cursor is declared once, and each caller supplies the values.
A parameter is a named placeholder in the cursor's query. You declare it in the cursor header and give it a value when you open the cursor. Each cursor definition still has one query. Parameters change only the values in it, not its structure.
Declaring a parameterized cursor
The syntax is:
CURSOR cursor_name (parameter_name [IN] datatype [{:= | DEFAULT} value], ...) IS
select_statement;These rules apply to the parameter list:
- Parameters are always
IN. You may write the keyword, but you cannot declareOUTorIN OUTcursor parameters, and you cannot assign to a parameter. - Give the datatype without a constraint. Write
NUMBER, notNUMBER(4), andVARCHAR2, notVARCHAR2(30). You can use%TYPEto borrow a column's type. - A parameter with a
DEFAULTcan be left out when the cursor is opened. - A parameter is visible only inside the cursor's query. The block's other code cannot see it.
- A parameter stands for a value, not an identifier. You cannot use one for a table or column name. That needs dynamic SQL, which the REF CURSOR chapter covers.
DECLARE
CURSOR c_emp (p_dept employees.department_id%TYPE,
p_min_sal NUMBER DEFAULT 0) IS
SELECT last_name, salary
FROM employees
WHERE department_id = p_dept
AND salary >= p_min_sal
ORDER BY last_name;
BEGIN
FOR r IN c_emp(50, 3000) LOOP
DBMS_OUTPUT.PUT_LINE(r.last_name || ': ' || r.salary);
END LOOP;
END;
/The p_ prefix is a naming convention. The next section shows why it matters.
Passing arguments
You pass arguments in parentheses after the cursor name. This works in OPEN and in a cursor FOR loop. The same positional and named rules apply as for subprogram calls.
| Style | Example | Notes |
|---|---|---|
| Positional | `c_emp(50, 3000)` | Arguments match parameters by order. |
| Named | `c_emp(p_min_sal => 3000, p_dept => 50)` | Order does not matter. |
| Mixed | `c_emp(50, p_min_sal => 3000)` | Positional arguments must come first. |
| Defaults | `c_emp(50)` | `p_min_sal` takes its default of 0. |
An argument can be a literal, a variable, or an expression. Oracle evaluates it once, at open time.
DECLARE
CURSOR c_emp (p_dept employees.department_id%TYPE,
p_min_sal NUMBER DEFAULT 0) IS
SELECT last_name, salary
FROM employees
WHERE department_id = p_dept
AND salary >= p_min_sal
ORDER BY last_name;
l_dept employees.department_id%TYPE := 50;
BEGIN
FOR r IN c_emp(p_min_sal => 4000, p_dept => l_dept) LOOP
DBMS_OUTPUT.PUT_LINE(r.last_name || ': ' || r.salary);
END LOOP;
END;
/What happens at OPEN
When the cursor opens, Oracle binds the argument values to the parameters. It then runs the query and fixes the result set. Changing a variable afterward does not change the rows the open cursor returns.
A cursor FOR loop does the open, fetch, and close steps for you. A manual loop does them explicitly, which is the case shown next.
Reusing one cursor with different arguments
You can use one cursor many times if you close it between uses. This block walks through departments 50 and 60 with a manual loop.
DECLARE
CURSOR c_emp (p_dept employees.department_id%TYPE) IS
SELECT last_name
FROM employees
WHERE department_id = p_dept
ORDER BY last_name;
l_name employees.last_name%TYPE;
l_dept employees.department_id%TYPE := 50;
BEGIN
WHILE l_dept <= 60 LOOP
DBMS_OUTPUT.PUT_LINE('Department ' || l_dept);
OPEN c_emp(l_dept);
LOOP
FETCH c_emp INTO l_name;
EXIT WHEN c_emp%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(' ' || l_name);
END LOOP;
CLOSE c_emp;
l_dept := l_dept + 10;
END LOOP;
END;
/Opening a cursor that is already open raises CURSOR_ALREADY_OPEN (ORA-06511). Oracle does not close the old result set and start again. You must close it first.
DECLARE
CURSOR c_emp (p_dept NUMBER) IS
SELECT last_name FROM employees WHERE department_id = p_dept;
BEGIN
OPEN c_emp(50);
OPEN c_emp(60); -- raises ORA-06511
EXCEPTION
WHEN CURSOR_ALREADY_OPEN THEN
DBMS_OUTPUT.PUT_LINE('Cursor was already open');
IF c_emp%ISOPEN THEN
CLOSE c_emp;
END IF;
END;
/A cursor FOR loop opens its cursor itself. If you use a cursor in a FOR loop while it is already open, you get the same error.
Nested loops: the main use case
Parameters are most useful when an inner loop depends on the current row of an outer loop. The inner cursor takes the outer row's key as an argument.
DECLARE
CURSOR c_dept IS
SELECT department_id, department_name
FROM departments
WHERE department_id IN (50, 60)
ORDER BY department_id;
CURSOR c_emp (p_dept employees.department_id%TYPE) IS
SELECT last_name, salary
FROM employees
WHERE department_id = p_dept
ORDER BY last_name;
BEGIN
FOR d IN c_dept LOOP
DBMS_OUTPUT.PUT_LINE(d.department_name);
FOR e IN c_emp(d.department_id) LOOP
DBMS_OUTPUT.PUT_LINE(' ' || e.last_name || ': ' || e.salary);
END LOOP;
END LOOP;
END;
/Each pass through the outer loop opens c_emp with a new argument. The inner FOR loop closes it when it ends, so the next pass can open it again.
This pattern runs one inner query per outer row. For large tables, a single join is usually faster. Use the nested form when the inner work is procedural, or when the two levels need different handling.
Gotchas
Parameter names that match column names
Inside the query, Oracle resolves a name as a column first. A parameter with the same name as a column never gets used.
DECLARE
CURSOR c_bad (department_id NUMBER) IS
SELECT last_name
FROM employees
WHERE department_id = department_id; -- compares the column to itself
l_count PLS_INTEGER := 0;
BEGIN
FOR r IN c_bad(50) LOOP
l_count := l_count + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE(l_count || ' rows'); -- every employee with a department
END;
/The condition is true for every row whose department_id is not null. The cursor returns far more rows than department 50 holds, and no error is raised. Prefix parameters with p_ to avoid this.
NULL arguments
If you pass NULL for p_dept, the condition department_id = p_dept is never true. The cursor opens and returns no rows. Check the argument first, or write the condition to handle NULL on purpose:
WHERE (p_dept IS NULL OR department_id = p_dept)That form is easy to write, but it can lead the optimizer to a worse plan than a plain equality. Use it only when callers need the "all departments" case.
Mismatched argument counts and types
A call with too many arguments, or with a missing argument that has no default, fails at compile time (PLS-00306). An argument of the wrong type is converted implicitly when possible. Passing a string where a NUMBER is expected relies on that conversion and can fail at run time. Pass values of the declared type.
Common errors at a glance
| Symptom | Likely cause | Fix |
|---|---|---|
| ORA-06511 `CURSOR_ALREADY_OPEN` | `OPEN` on an open cursor | `CLOSE` first, or test `%ISOPEN`. |
| PLS-00306 wrong number or types of arguments | Missing or extra argument | Match the parameter list or add defaults. |
| Cursor returns too many rows | Parameter name equals a column name | Rename the parameter with `p_`. |
| Cursor returns no rows | `NULL` argument | Validate the argument or handle `NULL` in the query. |
| Compile error on `p_x NUMBER(5)` | Constraint in the parameter type | Use `NUMBER` or `%TYPE`. |
Exercise
Write a block that declares a cursor c_sal (p_dept NUMBER, p_min NUMBER DEFAULT 5000) returning last_name and salary for a department with salary at or above p_min. Open it with a cursor FOR loop for department 80 using the default minimum. Then do the same for department 50 with a minimum of 3000, using named notation.
Show answer
DECLARE CURSOR csal (pdept NUMBER, pmin NUMBER DEFAULT 5000) IS SELECT lastname, salary FROM employees WHERE departmentid = pdept AND salary >= pmin ORDER BY lastname; BEGIN FOR r IN csal(80) LOOP DBMSOUTPUT.PUTLINE(r.lastname || ': ' || r.salary); END LOOP; FOR r IN csal(pmin => 3000, pdept => 50) LOOP DBMSOUTPUT.PUTLINE(r.lastname || ': ' || r.salary); END LOOP; END; /
Exercise
A developer writes CURSOR c (salary NUMBER) IS SELECT last_name FROM employees WHERE salary > salary; and opens it with c(10000). It returns no rows, and no error appears. Why, and how do you fix it?
Show answer
Inside the query, salary resolves to the column, not the parameter, so the condition compares each row's salary with itself. salary > salary is never true. Rename the parameter, for example p_salary, and write WHERE salary > p_salary.
Exercise
A block opens c_emp(50) in a manual loop and, in the same block, opens c_emp(60) without closing the first. What is raised, and what are two ways to prevent it?
Show answer
ORA-06511, CURSOR_ALREADY_OPEN, is raised. Prevent it by calling CLOSE c_emp before the second OPEN, or by testing IF NOT c_emp%ISOPEN THEN OPEN .... A cursor FOR loop also avoids it, because the loop closes the cursor when it ends.