Explanation of Cursor, Command to control Cursor with an example

A cursor is a working area where an SQL statement is executed. It is used to process individual rows returned by the database system for a query.

There are two types of cursor

  1. Implicit cursor: It is a predefined cursor that is associated with DML hence the declaration is not required in this cursor. Some of the attributes used as implicit cursors are %FOUND, %NOT FOUND, %OPEN, %ROWCOUNT.
  2. Explicit cursor: It is a user-defined cursor hence the declaration is required for this cursor. It is associated with the SELECT statement of SQL which returns more than one row. The associated commands used are DECLARE, OPEN, CLOSE, FETCH, etc.

Various cursor attributes

Cursor attributesDescription
%FOUNDReturns true if the DML statement affects at least one row else returns false.
%NOT FOUNDReturns true if no row is affected by the DML statement else returns false
%OPENReturns false implicit function or explicit function is close and returns true if the explicit function is open.
%ROWCOUNTReturns the number of affected rows
DECLAREUsed to declare the curser in declare section
OPENUsed to open the cursor in the execution section
CLOSEUsed to close the cursor in the execution section before the end of PL/SQL.
FETCHUsed to fetch the data from the cursor

Now let’s have a look at the example

DECLARE
	C_id customer.id
	C_name customer.name
	Cursor C1 IS SELECT id, name from customer;
BEGIN
OPEN C1
LOOP
	FETH C1 INTO C_id, C_name;
	EXIT WHEN C1%NOTFOUND;
	Dbms.output.put_line(“id:=”||C_id||”name:=”||C_name);
END LOOP;
CLOSE C1;
END;
/