Cursors that are used in PL/SQL are of two types:
- Implicit cursor
- Explicit cursor
Implicit Cursor
PL/SQL declares an implicit cursor for every DML command, and queries that return a single row. The name of the implicit cursor is SQL. It can be used directly without any declaration.
Explicit cursor
Explicit cursors are SELECT statements that are Declared explicitly in the declaration section of the current block or in a package specification. Use OPEN, FETCH, and CLOSE in the execution or exception sections of the programs.
The following example uses a cursor to select the five highest paid employees from the emps table.
Input Table
SQL> SELECT ename, empno, sal FROM emps RDER BY sal DESC;
ENAME EMPNO SAL
-------------------- ---------- ----------
kavitha 17 20000
deepa 8 15000
kala 15 15000
subha 9 15000
shobana 27 10000
Cursor example
Create the table named as temp
SQL> create table temp (my_sal number (5), my_empno number (5), my_ename varchar2 (20));
Table created.
SQL>
1 DECLARE
2 CURSOR c1 is
3 SELECT ename, empno, sal FROM emps
4 ORDER BY sal DESC;
5 my_ename CHAR (10);
6 my_empno NUMBER (4);
7 my_sal NUMBER (7,2);
8 BEGIN
9 OPEN c1;
10 FOR i IN 1...5 LOOP
11 FETCH c1 INTO my_ename, my_empno, my_sal;
12 EXIT WHEN c1%NOTFOUND;
13 INSERT INTO temp VALUES (my_sal, my_empno, my_ename);
14 COMMIT;
15 END LOOP;
16 CLOSE c1;
17* END;
SQL> /
PL/SQL procedure successfully completed.
Output Table
SQL> SELECT * FROM temp ORDER BY my_sal DESC
MY_SAL MY_EMPNO MY_ENAME
---------- ---------- --------------------
20000 17 kavitha
15000 8 deepa
15000 15 kala
15000 9 subha
10000 27 shobana
|