Sub topic 1
What a cursor is
Prerequisites
This chapter assumes you know basic SQL (SELECT, UPDATE, WHERE), the structure of an anonymous PL/SQL block (DECLARE, BEGIN, EXCEPTION, END), PL/SQL variables, and simple exception handling. The examples use the HR sample employees table.
What a cursor is
When Oracle runs a SQL statement, it stores the statement and its results in a private memory area called the context area. A cursor is the handle your PL/SQL code uses to reach that area. A query can return many rows, and a cursor lets your code move through them.
Implicit cursors: SQL%ROWCOUNT and friends
Oracle creates an implicit cursor for each INSERT, UPDATE, DELETE, and single-row SELECT INTO. You do not declare it. You read its attributes through the prefix SQL.
BEGIN
UPDATE employees
SET salary = salary * 1.05
WHERE department_id = 50;
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT || ' rows updated');
END;
/SQL%ROWCOUNT holds the number of rows the most recent DML statement affected. SQL%FOUND and SQL%NOTFOUND tell you whether it affected any rows. Read these attributes right after the statement, because the next statement overwrites them.
Explicit cursors: declare, open, fetch, close
Use an explicit cursor when a query returns several rows and you need to process each one. You control four steps: declare the query, open it, fetch rows one at a time, and close it.
DECLARE
CURSOR c_emp IS
SELECT employee_id, last_name, salary
FROM employees
WHERE department_id = 50
ORDER BY last_name;
r_emp c_emp%ROWTYPE;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp INTO r_emp;
EXIT WHEN c_emp%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(r_emp.last_name || ': ' || r_emp.salary);
END LOOP;
CLOSE c_emp;
END;
/The variable r_emp is a %ROWTYPE record, so its fields match the columns in the cursor query.
Cursor attributes
Explicit cursors expose these attributes:
| Attribute | Meaning |
|---|---|
| %ISOPEN | TRUE if the cursor is open |
| %FOUND | TRUE if the last fetch returned a row |
| %NOTFOUND | TRUE if the last fetch returned no row |
| %ROWCOUNT | Number of rows fetched so far |
Exercise
Given UPDATE employees SET salary = salary * 1.05 WHERE department_id = 99; and no employee works in department 99, what does SQL%ROWCOUNT report right after the statement?
Show answer
It reports 0. The UPDATE raises no error, and SQL%NOTFOUND becomes TRUE.