Cursors
Cursors
Cursors
S.Naji
naji@nsbm.lk
Cursors
A cursor is a temporary work area created in the
system memory when a SQL statement is executed.
A cursor contains information on a select statement
and the rows of data accessed by it. This temporary
work area is used to store the data retrieved from
the database, and manipulate this data. A cursor can
hold more than one row, but can process only one
row at a time. The set of rows the cursor holds is
called theactive set.
Types of cursors
There are two types of cursors in PL/SQL:
Implicit cursors:
These are created by default when DML statements like, INSERT,
UPDATE, and DELETE statements are executed. They are also created
when a SELECT statement that returns just one row is executed.
Explicit cursors:
They must be created when you are executing a SELECT statement that
returns more than one row. Even though the cursor stores multiple records,
only one record can be processed at a time, which is called as current row.
When you fetch a row the current row position moves to next row.
Both implicit and explicit cursors have the same functionality, but they
differ in the way they are accessed.
S.No Attribute & Description
%FOUND
Returns TRUE if an INSERT, UPDATE, or
1 DELETE statement affected one or more rows or a
SELECT INTO statement returned one or more
rows. Otherwise, it returns FALSE.
%NOTFOUND
The logical opposite of %FOUND. It returns TRUE
2 if an INSERT, UPDATE, or DELETE statement
affected no rows, or a SELECT INTO statement
returned no rows. Otherwise, it returns FALSE.
%ISOPEN
Always returns FALSE for implicit cursors, because
3
Oracle closes the SQL cursor automatically after
executing its associated SQL statement.
%ROWCOUNT
Returns the number of rows affected by an INSERT,
4
UPDATE, or DELETE statement, or returned by a
SELECT INTO statement.
Implicit Cursor
Example
CURSOR c1
IS
SELECT course_number
from courses_tbl
where course_name = name_in;
DECLARE c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is SELECT id, name, address
FROM customers;
BEGIN OPEN c_customers;
LOOP FETCH c_customers into c_id, c_name,
c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || '
' || c_addr);
END LOOP;
CLOSE c_customers;
END; /
Cursor Declaration
DECLARE
CURSOR employee_cur IS
SELECT * FROM employee
FOR UPDATE OF salary;
BEGIN
FOR employee_rec IN employee_cur
LOOP
UPDATE employee
SET salary = 10000
WHERE CURRENT OF employee_cur;
END LOOP;
END;
/
Check the answer
CURSOR c_Registeredemployee IS
SELECT *
FROM employee
WHERE id IN ('01')
FOR UPDATE OF salary;
Continue….
BEGIN
-- Set up the cursor fetch loop.
v_salary := 100;
FOR v_employeeInfo IN c_Registeredemployee LOOP
• Table-based
• Cursor-based records
• User-defined records
Commit
Rollback
SAVEPOINT S1;
ROLLBACK TO S1;