OPEN-FOR Statement
The OPEN-FOR
statement assigns the cursor to a different query.
CREATE TABLE EMP (EMPNO NUMBER(4) NOT NULL,
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
SAL NUMBER(7, 2),
DEPTNO NUMBER(2));
INSERT INTO EMP VALUES (1, 'SMITH', 'CLERK', 800, 20);
INSERT INTO EMP VALUES (2, 'ALLEN', 'SALESMAN', 1600, 30);
INSERT INTO EMP VALUES (3, 'WARD', 'SALESMAN', 1250, 30);
INSERT INTO EMP VALUES (4, 'JONES', 'MANAGER', 2975, 20);
INSERT INTO EMP VALUES (5, 'MARTIN','SALESMAN', 1250, 30);
INSERT INTO EMP VALUES (6, 'BLAKE', 'MANAGER', 2850, 30);
INSERT INTO EMP VALUES (7, 'CLARK', 'MANAGER', 2850, 10);
INSERT INTO EMP VALUES (8, 'SCOTT', 'ANALYST', 3000, 20);
INSERT INTO EMP VALUES (9, 'KING', 'PRESIDENT',3000, 10);
INSERT INTO EMP VALUES (10,'TURNER','SALESMAN', 1500, 30);
INSERT INTO EMP VALUES (11,'ADAMS', 'CLERK', 1500, 20);
SQL>
SQL> SET SERVEROUTPUT ON
SQL>
SQL> DECLARE
2 TYPE t_emp_cursor IS REF CURSOR RETURN emp%ROWTYPE;
3 v_emp_cursor t_emp_cursor;
4 v_emp emp%ROWTYPE;
5 BEGIN
6 OPEN v_emp_cursor FOR SELECT * FROM emp WHERE empno < 5;
7 LOOP
8 FETCH v_emp_cursor INTO v_emp;
9 EXIT WHEN v_emp_cursor%NOTFOUND;
10 DBMS_OUTPUT.PUT_LINE('empno:' || v_emp.empno || ', name = ' || v_emp.ename ||', salary = ' || v_emp.sal);
11 END LOOP;
12 CLOSE v_emp_cursor;
13 END;
14 /
empno:1, name = SMITH, salary = 800
empno:2, name = ALLEN, salary = 1600
empno:3, name = WARD, salary = 1250
empno:4, name = JONES, salary = 2975
PL/SQL procedure successfully completed.
SQL>
Home »
Oracle »
PL/SQL »
Oracle »
PL/SQL »
Cursors:
- Cursors
- Cursors and FOR Loops
- OPEN-FOR Statement
- Unconstrained Cursors
Related: