What is cursor?
A Cursor is a pointer, which works on active set, I.e. which points to only one row at a time in the context area’s ACTIVE SET. A cursor is a construct of pl/sql, used to process multiple rows using a pl/sql block.
Types of cursors:
1) Implicit: declared for all DML and pl/sql statements.
By default it selects one row only.
2) Explicit: Declared and named by the programmer.
Use explicit cursor to individually process each row returned by a
Multiple statements, is called ACTIVE SET.
Allows the programmer to manually control explicit cursor in the
Pl/sql block
Life Cycle Of A Cursor:
a) declare: create a named sql area
b)Open: identify the active set.
c) Fetch: load the current row in to variables.
d)Close: release the active set.
a) %is open: evaluates to true if the cursor is open.
b) %not found: evaluates to true if the most recent fetch does not return a row
c) %found: evaluates to true if the most recent fetch returns a row.
d) %row count: evaluates to the total number of rows returned to far.
1) Declare
Vno emp.empno%type;
Vname emp.ename %type;
Cursor emp_cursor is
Select empno,ename
From emp;
Begin
Open cursor;
For I in 1..10 loop
Fetch emp_cursor into vno,vname;
Dbms_output.putline(to_char(vno) ||’ ‘||vname);
End if;
E nd;
2) Begin
Open emp_cursor;
Fetch when emp_cursor % rowcount >10 or
Emp_curor % not found;
Bdms_output_put_line(to_char(vno)||’ ‘|| vname);
End loop;
Close emp_cursor;
End;
CURSOR FOR
A) cursor for loop is a short cut to process explicit cursors
B) it has higher performance
C) cursor for loop requires only the declaration of the cursor, remaining things like opening, fetching and close are automatically take by the cursor for loop
Example:
1) Declare
Cursor emp_cursor is
Select empno,ename
From emp;
Begin
For emp_record in emp_cursor loop
Dbms_output.putline(emp_record.empno);
Dbms_output.putline(emp_record.ename)
End loop
End;
Can we create a cursor without declaring it?
Yes – by using cursor for loop using subqueries.
BEGIN
FOR emp_record IN ( SELECT empno, ename
FROM emp) LOOP
-- implicit open and implicit fetch occur
IF emp_record.empno = 7839 THEN
...
END LOOP; -- implicit close occurs
END;
a) for update clause:
1) use explicit locking to deny access for the duration of a transaction
2) lock the rows before update or delete
Ex : select …….
From…….
For update[ of column ref] [no_wait]
b) where current of clause?
1) use cursor to update or delete the current row
Where current of < column ref>
COMMENTS