You are on page 1of 4

CURSORS:

A CURSOR is a name given to the Active Set or Context Area or Temporary Memory Area which stores result of SELECT STATEMENT. Using CURSOR we can fetch one by one record from Context Area and process the record. Using CURSOR we can do row processing. CURSORS are of 2 types: EXPLICIT CURSORS: Follow below steps to use Explicit Cursors in PL/SQL program: - DECLARE CURSOR - OPEN CURSOR - FETCH RECORDS FROM CURSOR - CLOSE CURSOR DECLARE CURSOR CURSOR <NAME> IS SELECT STATEMENT; e.g: CURSOR C1 IS SELECT * FROM EMP; EXPLICIT CURSORS: Cursors declared by user. IMPLICIT CURSORS: Cursors declared by System.

OPEN CURSOR OPEN <NAME>; e.g: OPEN C1;

When CURSOR is open following things happens: - SELECT Statement is submitted to oracle server. - Oracle Server creates Context Area. - Records returned by the SELECT Statement are loaded into Context Area. - C1 points to the beginning of Context Area. FETCH RECORDS FROM CURSOR FETCH Statement is to fetch records from Context Area. FETCH <CURSORNAME> INTO <VARIABLES>

e.g:

FETCH C1 INTO X,Y,Z,

The statement fetches records from C1 and is assigned to the variables X,Y,Z, . A FETCH Statement fetches only one record at a time but to process multiple records keep the fetch statement inside a loop. CLOSING CURSOR Once processing is completed then close CURSOR. CLOSE <CURSORNAME> e.g: CLOSE C1;

CURSOR ATRRIBUTES
%FOUND, %NOTFOUND, %ROWCOUNT, %ISOPEN

Write a PL/SQL program to print all employees names and salaries


DECLARE CURSOR C1 IS SELECT ENAME, SAL FROM EMP; R C1%ROWTYPE; --CURSOR ROWTYPE RECORD IS ASSINGED --WHICH BELONGS TO C1 BEGIN OPEN C1; --CONTEXT AREA IS CREATED, DATA RETURN BY THE --SELECT STATEMENT IS LOADED IN C1 LOOP FETCH C1 INTO R; --ASSIGNED THE CURSOR RECORD TO R EXIT WHEN C1%NOTFOUND; DBMS_OUTPUT.PUT_LINE(R.ENAME||' '||R.SAL); END LOOP; CLOSE C1; END; O/P:-

Write a PL/SQL program to display top 5 employees name and salaries


DECLARE CURSOR C1 IS SELECT ENAME, SAL FROM EMP ORDER BY SAL DESC; R C1%ROWTYPE; BEGIN OPEN C1; LOOP FETCH C1 INTO R; EXIT WHEN C1%ROWTYPE>5; DBMS_OUTPUT.PUT_LINE(R.ENAME||' '||R.SAL); END LOOP; CLOSE C1; END; O/P:-

USING WHILE LOOP BEGIN OPEN C1; FETCH C1 IN R; WHILE (C1%FOUND) LOOP DBMS_OUTPUT.PUT_LINE(R.ENAME|| ||R.SAL);

FETCH C1 IN R; END LOOP; CLOSE C1; END; Here fetch statement is required 2 times, one to start the while loop and second to continue the while loop.

You might also like