2 Cursors
2 Cursors
What is a Cursor?
A cursor is like a bookmark you use to keep track of rows in a table. It allows us to go through
rows in a table one by one when we need to process each row individually.
Types of Cursors
When you run a simple query like INSERT, UPDATE, or SELECT INTO, PL/SQL automatically
creates an implicit cursor for you.
Code:
DECLARE
student_count NUMBER;
BEGIN
SELECT COUNT(*) INTO student_count FROM students;
DBMS_OUTPUT.PUT_LINE('Total students: ' || student_count);
END;
What Happens:
Unit: 4 - PL/SQL control statements and stored procedures Dr. Sulbha Gath Page 1
Explicit Cursor Example
Explicit cursors are created when you want to process rows one by one.
Code:
DECLARE
CURSOR student_cursor IS
SELECT name FROM students;
student_name students.name%TYPE;
BEGIN
OPEN student_cursor;
LOOP
FETCH student_cursor INTO student_name;
EXIT WHEN student_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Student Name: ' || student_name);
END LOOP;
CLOSE student_cursor;
END;
What Happens:
1. CURSOR student_cursor IS SELECT name FROM students; : You define a cursor that
selects student names.
2. OPEN student_cursor;: Opens the cursor and gets it ready to fetch rows.
3. FETCH student_cursor INTO student_name;: Reads one row from the table into the
variable student_name.
4. LOOP ... END LOOP;: Repeats the process until all rows are processed.
5. CLOSE student_cursor;: Closes the cursor when done.
Unit: 4 - PL/SQL control statements and stored procedures Dr. Sulbha Gath Page 2