Professional Documents
Culture Documents
Lecture4 - PL-SQL-Cursors Part1
Lecture4 - PL-SQL-Cursors Part1
Lecture4 - PL-SQL-Cursors Part1
PL/SQL
Introduction to Explicit Cursors
Objectives
Purpose
Context Area
4 Copyright © 2013, Oracle and/or its affiliates. All rights
reserved.
Introduction to Explicit Cursors
Explicit Cursors
Table
Explicit Cursor
100 King AD_PRES
101 Kochhar AD_VP
102 De Haan AD_VP
139 Seo ST_CLERK
Active set
9 Copyright © 2013, Oracle and/or its affiliates. All rights
reserved.
Introduction to Explicit Cursors
Active set
10 Copyright © 2013, Oracle and/or its affiliates. All rights
reserved.
Introduction to Explicit Cursors
Cursor
3 Close the cursor. pointer
No
Yes
DECLARE OPEN FETCH CLOSE
• Name an • Fill the active • Retrieve the • Test for • Release the
active set. set with data. current row existing rows. active set.
into
variables.
• Return to
FETCH if rows
are found.
Syntax:
CURSOR cursor_name IS
select_statement;
In the syntax:
cursor_name Is a PL/SQL identifier
select_statement Is a SELECT statement without an
INTO clause
Terminology
Summary
Objectives
Purpose
Structure of cursor_name%ROWTYPE
DECLARE
CURSOR emp_cursor IS
SELECT employee_id, last_name, salary FROM employees
WHERE department_id = 30;
v_emp_record emp_cursor%ROWTYPE;
...
DECLARE
CURSOR emp_dept_cursor IS
SELECT first_name, last_name, department_name
FROM employees e, departments d
WHERE e.department_id = d.department_id;
v_emp_dept_record emp_dept_cursor%ROWTYPE;
BEGIN
OPEN emp_dept_cursor;
LOOP
FETCH emp_dept_cursor INTO v_emp_dept_record;
EXIT WHEN emp_dept_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(v_emp_dept_record.first_name
||' – '||v_emp_dept_record.last_name
||' – '||v_emp_dept_record.department_name);
END LOOP;
CLOSE emp_dept_cursor;
END;
%ISOPEN Attribute
You can fetch rows only when the cursor is open. Use
the %ISOPEN cursor attribute before performing a fetch
to test whether the cursor is open. %ISOPEN returns
the status of the cursor: TRUE if open and FALSE if
not.
Example:
IF NOT emp_cursor%ISOPEN THEN
OPEN emp_cursor;
END IF;
LOOP
FETCH emp_cursor...
Terminology
Summary
Objectives
Purpose
Syntax:
FOR record_name IN cursor_name LOOP
statement1;
statement2;
. . .
END LOOP;
In the syntax:
• record_name Is the name of the implicitly
declared record (as cursor_name%ROWTYPE)
• cursor_name Is a PL/SQL identifier for the
previously declared cursor
FOR record_name IN cursor_name LOOP
statement1;
statement2;
. . .
END LOOP;
Guidelines:
• Do not declare the record that controls the loop
because it is declared implicitly.
• The scope of the implicit record is restricted to the
loop, so you cannot reference the record outside the
loop.
• You can access fetched data by
record_name.column_name.
BEGIN
FOR v_emp_record IN emp_cursor
LOOP
EXIT WHEN emp_cursor%ROWCOUNT > 5;
DBMS_OUTPUT.PUT_LINE( v_emp_record.employee_id
|| ' ' ||v_emp_record.last_name);
END LOOP;
END;
Terminology
Summary