Cursor
Cursor
Cursor
-------
Oracle creates a memory area, known as the context area, for processing an SQL
statement.
A cursor is a pointer to this context area. PL/SQL controls the context area
through a cursor. A cursor holds the rows (one or more) returned by a SQL
statement.
The set of rows the cursor holds is referred to as the active set.
Why we go for -> whenever we are fetching data, we need to store the fetched data
in a
variable. By using a cursor, you can use the same variables (or a
record
type) to hold the data.
Implicit Cursor :
---------------
Explicit Cursor :
----------------
Explicit cursors are programmer-defined cursors for gaining more control over the
context area. An explicit cursor 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.
Cursor Attributes :
-------------------
Both Implicit cursor and the explicit cursor has certain attributes that can be
accessed. These
attributes give more information about the cursor operations. Below are the
different cursor attributes
and their usage.
Syntax :
--------
DECLARE
CURSOR cursor_name IS select_statement;
cur_variable cursor_name%rowtype;
BEGIN
OPEN cursor_name;
FETCH cursor_name INTO cur_variable;
CLOSE cursor_name;
END;
Example Program :
----------------
DECLARE
CURSOR guru99_det
IS
SELECT emp_name FROM emp;
lv_emp_name emp.emp_name%type;
BEGIN
OPEN guru99_det;
LOOP
FETCH guru99_det INTO lv_emp_name;
IF guru99_det%NOTFOUND
THEN
EXIT;
END IF;
Dbms_output.put_line(‘Employee Fetched:‘||lv_emp_name);
END LOOP;
Dbms_output.put_line(‘Total rows fetched is‘||guru99_det%R0WCOUNT);
CLOSE guru99_det;
END:
/
"FOR LOOP" statement can be used for working with cursors. We can give the cursor
name
instead of range limit in the FOR loop statement so that the loop will work from
the first record
of the cursor to the last record of the cursor.
Why we go for? The cursor variable, opening of cursor, fetching and closing of the
cursor will be
done implicitly by the FOR loop.
Syntax :
--------
DECLARE
CURSOR <cursor_name> IS <SELECT statement>;
BEGIN
FOR I IN <cursor_name> LOOP
. . . . .
END LOOP;
END;