Cursors
Cursors
* When an SQL statement is processed, Oracle creates a memory area known as context
area.
* A cursor is a pointer to this context area.
* It contains all information needed for processing the statement.
* In PL/SQL, the context area is controlled by Cursor.
* There are two types of cursors:
1.Implicit Cursors
2.Explicit Cursors
Implicit Cursor:
The implicit cursors are automatically generated by Oracle while an SQL statement
is executed
These are created, when DML statements like INSERT, UPDATE, DELETE etc. are
executed.
These cursors will have SQL as cursor name.
Example:
DECLARE
total_rows number(2);
BEGIN
UPDATE employees
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no Employee updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' Employees updated ');
END IF;
END;
Cursor Attributes:
the following attributes are used to check status of the cursor,
%FOUND:
Its return value is TRUE if DML statements like INSERT, DELETE and UPDATE
affect at least one row, Otherwise it returns FALSE.
%NOTFOUND:
Its return value is TRUE if DML statements like INSERT, DELETE and UPDATE
affect no row, Otherwise it returns FALSE. It is a just opposite of %FOUND.
%ISOPEN:
It always returns FALSE for implicit cursors, because the SQL cursor is
automatically closed after executing its associated SQL statements.
%ROWCOUNT:
It returns the number of rows affected by DML statements like INSERT, DELETE,
and UPDATE .
Explicit Cursors:
* defined by the programmers to gain more control over the context area.
* These cursors should be defined in the declaration section of the PL/SQL block.
* It is created on a SELECT statement which returns more than one row.
syntax:
CURSOR cursor_name IS select_statement;
Steps to create Explicit cursor:
You must follow these steps while working with an explicit cursor.
CURSOR name IS
SELECT statement;
OPEN cursor_name;
Close cursor_name;
example:
declare
cursor empcur is select * from emp where salary<36000;
emprec emp%rowtype;
begin
open empcur;
loop
fetch empcur into emprec;
exit when empcur%NOTFOUND;
dbms_output.put_line(emprec.empid || emprec.empname || emprec.salary ||
emprec.dept);
end loop;
close empcur;
end;
/