PL/SQL Cursors

PL/SQL Cursors

PL/SQL uses implicit and explicit cursors.
PL/SQL declare a implicit cursor for each operation to data manipulation in SQL.
If you want precise control over the queries, you can declare a explicit cursor;
You can define a explicit cursor for the queries which returns more than one row.

1. Implicit Cursors

The implicit cursors are managed automatically by the PL/SQL.

2. Explicit Cursors

When you need precise control over the outcome of the queries, must be declared a explicit cursor in PL/SQL.
The commands for a explicit cursor: OPEN, FETCH and CLOSE. First time the cursor must be opened through the OPEN command. Then you can run FETCH repeated until all records have been read or you can use BULK COLLECT clause to read all recording only once. For close a cursor uses the CLOSE command.

The attributes of the cursors

The attributes of the implicit cursors can return information about DML and DDL execution commands such as INSERT, UPDATE, DELETE, SELECT INTO, COMMIT or ROLLBACK.
The cursor attributes are: %FOUND, %ISOPEN, %NOTFOUND and %ROWCOUNT.

SQL%FOUND

Until SQL data manipulation is executed, the attribute %FOUND is NULL.

Example:

CREATE TABLE stu_temp AS SELECT * FROM students;
DECLARE
	v_id NUMBER:=3;
BEGIN
	DELETE FROM stu_temp WHERE student_id = v_id;
	IF SQL%FOUND THEN 
	INSERT INTO stu_temp(student_id, first_name, last_name, gender) 
	SELECT s.student_id, s.first_name, s.last_name, s.gender 
	FROM students s
	WHERE s.student_id=v_id;
	END IF;
END;

SQL%ISOPEN

Oracle database closes the cursor automatically after execution of commands. You must check if the cursor is open.

SQL%NOTFOUND

%NOTFOUND is the opposite attribute of %FOUND.

SQL%ROWCOUNT

%ROWCOUNT returns the number of records affected by one of the commands like INSERT, UPDATE or DELETE.

Example: Using SQL%ROWCOUNT

CREATE TABLE stu_temp AS SELECT * FROM students;
DECLARE
	v_id NUMBER:=3;
BEGIN
	DELETE FROM stu_temp WHERE student_id = v_id;
	DBMS_OUTPUT.PUT_LINE('Number of students deleted: '||SQL%ROWCOUNT); 
END;

%ROWTYPE

DECLARE
	stu_row students%ROWTYPE; 
BEGIN
	SELECT * INTO stu_row 
	FROM students WHERE student_id=3;
	DBMS_OUTPUT.PUT_LINE('First name: '||stu_row.first_name);
	DBMS_OUTPUT.PUT_LINE('Last name: '||stu_row.last_name);
END;