Professional Documents
Culture Documents
Cursors
Cursors
CURSOR MANIPULATION
Types Of Cursors
IMPLICIT CURSOR
1. A cursor is automatically associated with every DML
(Data Manipulation) statement (UPDATE, DELETE,
INSERT).
2. All UPDATE and DELETE statements have cursors that
identify the set of rows that will be affected by the
operation.
3. An INSERT statement needs a place to receive the data
that is to be inserted in the database; the implicit cursor
fulfills this need.
BEGIN
UPDATE student
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT);
END;
EXPLICIT CURSOR
EXPLICIT CURSOR
The process of working with an explicit cursor consists
of the following steps:
DECLARING the cursor. This initializes the cursor
into memory.
OPENING the cursor. The previously declared
cursor can now be opened; memory is allotted.
FETCHING the cursor. The previously declared
and opened cursor can now retrieve data; this is
the process of fetching the cursor.
CLOSING the cursor. The previously declared,
opened, and fetched cursor must now be closed to
release memory allocation.
7
CSC Proprietary and Confidential
Example
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is SELECT id, name, address
FROM customers;
BEGIN
OPEN c_customers;
LOOP
CLOSE c_customers;
END;
10
Example
DECLARE
CURSOR c_student IS
SELECT student_id, last_name, first_name
FROM student
WHERE student_id < 110;
BEGIN
FOR r_student IN c_student
LOOP
INSERT INTO table_log
VALUES(r_student.last_name);
END LOOP;
END;
CSC Proprietary and Confidential
11
This enables a cursor to generate a specific result set, which is, on the
one hand, more narrow, but on the other hand, reusable.
A cursor of all the data from the zipcode table may be very useful, but
it would be more useful for certain data processing if it held information
for only one state.
FROM zipcode
12
13
Example
DECLARE
cursor c(no number) is select * from emp_information where emp_no
= no;
tmp emp_information%rowtype;
BEGIN
OPEN c(4);
FOR tmp IN c(4) LOOP
dbms_output.put_line('EMP_No: '||tmp.emp_no);
dbms_output.put_line('EMP_Name: '||tmp.emp_name);
dbms_output.put_line('EMP_Dept: '||tmp.emp_dept);
dbms_output.put_line('EMP_Salary:'||tmp.emp_salary);
END Loop;
CLOSE c;
END;
CSC Proprietary and Confidential
14
END
CSC Proprietary and Confidential
10/29/15
15
15