Cursor
Cursor
FIRST_NAME VARCHAR2(50),
LAST_NAME VARCHAR2(50),
AGE NUMBER,
GRADE CHAR(2)
);
INSERT INTO STUDENT (STUDENT_ID, FIRST_NAME, LAST_NAME, AGE, GRADE) VALUES (1, 'John', 'Doe',
20, 'A');
INSERT INTO STUDENT (STUDENT_ID, FIRST_NAME, LAST_NAME, AGE, GRADE) VALUES (2, 'Jane',
'Smith', 21, 'B');
INSERT INTO STUDENT (STUDENT_ID, FIRST_NAME, LAST_NAME, AGE, GRADE) VALUES (3, 'Jim', 'Brown',
19, 'C');
IMPLICIT CURSOR
DECLARE
v_first_name STUDENT.FIRST_NAME%TYPE;
v_last_name STUDENT.LAST_NAME%TYPE;
v_age STUDENT.AGE%TYPE;
v_grade STUDENT.GRADE%TYPE;
BEGIN
FOR student_record IN (SELECT FIRST_NAME, LAST_NAME, AGE, GRADE FROM STUDENT) LOOP
v_first_name := student_record.FIRST_NAME;
v_last_name := student_record.LAST_NAME;
v_age := student_record.AGE;
v_grade := student_record.GRADE;
END LOOP;
END;
EXAMPLE 2
Begin
loop
End loop;
End;
You define a cursor, open it, fetch rows from it, and then close it when done.
Open the Cursor: Allocate memory and execute the SQL statement.
Close the Cursor: Release the memory allocated for the cursor.
DECLARE
CURSOR student_cursor IS
v_last_name STUDENT.LAST_NAME%TYPE;
v_age STUDENT.AGE%TYPE;
v_student_id STUDENT.STUDENT_ID%TYPE;
BEGIN
OPEN student_cursor;
LOOP
END LOOP;
CLOSE student_cursor;
END;
Implicit Cursor
Automatic: Oracle automatically creates this when you run a SQL query.
Less Control: You can’t control it as much; it’s just a quick way to fetch data.
Usage: Ideal for simple queries where you don’t need to manage the cursor lifecycle.
Example: You directly run a loop over a SQL query and print results. No need to declare or manage the
cursor.
Explicit Cursor
More Control: You can open, fetch, and close it. This gives you more flexibility, especially for complex
queries.
Usage: Useful when you need to process rows one at a time or perform additional logic between
fetches.
Example: You declare the cursor, open it, fetch data in a loop, and then close it when done.
Key Points
Output: Both types can produce the same output, but explicit cursors let you manage the fetching
process more precisely.
When to Use: