Opening multiple queries using the same cursor variable : Cursor Open « Cursor « Oracle PL/SQL Tutorial






SQL> create table product(
  2     product_id number(4)     not null,
  3     product_description varchar2(20) not null
  4  );

Table created.

SQL>
SQL> insert into product values (1,'Java');

1 row created.

SQL> insert into product values (2,'Oracle');

1 row created.

SQL> insert into product values (3,'C#');

1 row created.

SQL> insert into product values (4,'Javascript');

1 row created.

SQL> insert into product values (5,'Python');

1 row created.

SQL>
SQL>
SQL> create table company(
  2     product_id        number(4)    not null,
  3     company_id          NUMBER(8)    not null,
  4     company_short_name  varchar2(30) not null,
  5     company_long_name   varchar2(60)
  6  );

Table created.

SQL> insert into company values(1,1001,'A Inc.','Long Name A Inc.');

1 row created.

SQL> insert into company values(1,1002,'B Inc.','Long Name B Inc.');

1 row created.

SQL> insert into company values(1,1003,'C Inc.','Long Name C Inc.');

1 row created.

SQL> insert into company values(2,1004,'D Inc.','Long Name D Inc.');

1 row created.

SQL> insert into company values(2,1005,'E Inc.','Long Name E Inc.');

1 row created.

SQL> insert into company values(2,1006,'F Inc.','Long Name F Inc.');

1 row created.

SQL>
SQL> DECLARE
  2    TYPE rc is REF CURSOR;
  3    refCursorValue rc;
  4    productRecord product%ROWTYPE;
  5    v_product_description VARCHAR2(20);
  6    v_company_short_name VARCHAR2(30);
  7  BEGIN
  8    OPEN refCursorValue FOR SELECT *from product;
  9
 10    LOOP
 11      FETCH refCursorValue INTO productRecord;
 12      EXIT WHEN refCursorValue%NOTFOUND;
 13      dbms_output.put_line(to_char(productRecord.product_id)||' '||
 14      rpad(productRecord.product_description,20,' '));
 15    END LOOP;
 16
 17    OPEN refCursorValue FOR SELECT h.product_description,o.company_short_name
 18                  FROM company o,product h
 19                  WHERE o.product_id =h.product_id;
 20
 21    LOOP
 22      FETCH refCursorValue INTO v_product_description,v_company_short_name;
 23      EXIT WHEN refCursorValue%NOTFOUND;
 24      dbms_output.put_line(rpad(v_product_description,20,' ')||' '||rpad(v_company_short_name,30,' '));
 25    END LOOP;
 26    CLOSE refCursorValue;
 27  END;
 28  /
1 Java
2 Oracle
3 C#
4 Javascript
5 Python
Java                 A Inc.
Java                 B Inc.
Java                 C Inc.
Oracle               D Inc.
Oracle               E Inc.
Oracle               F Inc.

PL/SQL procedure successfully completed.

SQL>
SQL>
SQL> drop table product;

Table dropped.

SQL> drop table company;

Table dropped.

SQL>








25.3.Cursor Open
25.3.1.An example of opening a cursor variable
25.3.2.Open cursor with a dynamic select statement
25.3.3.Opening multiple queries using the same cursor variable