PL/SQL Cursor :-
When an SQL statement is processed, Oracle creates a memory area
known as context area or work area. This work area is private to SQL’s operations. 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. A cursor
contains information on a select statement and the rows of data accessed by it. It allows
user to access the stored information in it. The major
function of a cursor is to retrieve data, one row at a time, from a result set. Cursors
are used when the user needs to update records in a singleton fashion or in a row by row
manner, in a database table. The Data that is stored in the Cursor is called the Active
Data Set.
Types of cursor :-
1. Implicit cursor
2. Explicit cursor
1.) Implicit cursor :- If the Oracle engine opened a cursor for its internal processing
it is known as an Implicit Cursor. The implicit cursors are automatically generated
by Oracle while an SQL statement is executed. These are created by default to
process the statements when DML statements like INSERT, UPDATE, DELETE etc. are
executed.
2.) Explicit cursor :- Auser-defined cursor is known as an Explicit Cursor. An
explicit cursor is defined in the declaration section of the PL/SQL Block. It is
created on a SELECT Statement which returns more than one row.
Syntax :-
DECLARE
CURSOR <cursor_name> IS <SELECT statement^>
<cursor_variable declaration>
BEGIN
OPEN <cursor_name>;
FETCH <cursor_name> INTO <cursor_variable>;
……..
/* process the records;*/
………
. CLOSE <cursor_name>;
END;
There are four steps in using an Explicit Cursor :-
1.) DECLARE :- Declare the cursor in the Declaration section.It defines the cursor with
a name and the associated SELECT statement.
2.) OPEN :- It is used to allocate memory for the cursor and make it easy to fetch
the rows returned by the SQL statements into it.
3.) FETCH :- It is used to access one row at a time.
4.) CLOSE :- Once all the record is fetched now, we need to close the cursor so that
the memory allocated to this context area will be released. It is used to release the
allocated memory.
CURSOR ATTRIBUTES : -
Both Implicit cursor and the explicit cursor has certain attributes that can be
accessed. These are as follows –
%FOUND - It returns the Boolean result 'TRUE' if the most recent fetch operation
fetched a record successfully, else it will return FALSE.
%NOTFOUND - This works oppositely to %FOUND it will return 'TRUE' if the most
recent fetch operation could not able to fetch any record.
%ISOPEN - It returns Boolean result 'TRUE' if the given cursor is already opened,
else it returns 'FALSE'
%ROWCOUNT - It returns the numerical value. It gives the actual count of records that
got affected by the DML activity.