Cursor
Cursor
Cursor
A PL/SQL cursor is a pointer that points to the result set of an SQL query against database tables.
PL/SQL
Cursor
Let’s examine each step in greater detail.
First, you declare the name of the cursor cursor_name after the CURSOR keyword. The name of the
cursor can have up to 30 characters in length and follows the naming rules of identifiers in PL/SQL.
It is important to note that cursor’s name is not a variable so you cannot use it as a variable such as
assigning it to other cursor or using it in an expression. The parameter1,parameter2… are
optional elements in the cursor declaration. These parameters allow you to pass arguments into the
cursor. The RETURN return_specification is also an optional part.
Second, you specify a valid SQL statement that returns a result set where the cursor points to.
Third, you can indicate a list of columns that you want to update after the FOR UPDATE OF. This part
is optional so you can omit it in the CURSOR declaration.
Here is an example of declaring a cursor:
1 CURSOR cur_chief IS
2 SELECT first_name,
3 last_name,
4 department_name
5 FROM employees e
6 INNER JOIN departments d ON d.manager_id = e.employee_id;
We retrieved data from employees and departments tables using the SELECTwith the INNER JOIN clause
and set the cur_chief cursor to this result set.
Opening a PL/SQL Cursor
After declaring a cursor, you can open it by using the following syntax:
1 OPEN cur_chief;
The fetch action retrieves data and fills the record or the variable list. You can manipulate this data in
memory. You can fetch the data until there is no record found in active result set.
1 LOOP
2 -- fetch information from cursor into record
3 FETCH cur_chief INTO r_chief;
4
5 EXIT WHEN cur_chief%NOTFOUND;
6
7 -- print department - chief
8 DBMS_OUTPUT.PUT_LINE(r_chief.department_name || ' - ' ||
9 r_chief.first_name || ',' ||
10 r_chief.last_name);
11 END LOOP;
1 CLOSE cursor_name;
And here is an example of closing the cur_chief cursor:
1 CLOSE cur_chief;
Attribute Description
cursor_name%NOTFOUND returns TRUE if record was not fetched successfully by cursor cursor_name
cursor_name%ROWCOUNT returns the number of records fetched from the cursor cursor_name at the time
we test %ROWCOUNT attribute
cursor_name%ISOPEN returns TRUE if the cursor cursor_name is open
“}