Pass the table name to the cursor

advertisements

Guys is it possible to pass the table name from one cursor to another. kindly let me the other way.

CURSOR  R IS SELECT TABLE_NAME FROM RESOURCE ;

CURSOR S(TAB VARCHAR2) IS SELECT  username from TAB where sid=1291;

is there another way to pass the table to a cursor.


To expand on JackPDouglas' answer, you cannot utilize a param name as the [table] name in a cursor. You must utilize dynamic sql into a REF CURSOR

http://download.oracle.com/docs/cd/B10500_01/appdev.920/a96590/adg09dyn.htm#24492

CREATE OR REPLACE PROCEDURE dynaQuery(
       TAB IN VARCHAR2,
       sid in number ,
       cur OUT NOCOPY sys_refcursor) IS
 query_str VARCHAR2(200);
BEGIN
    query_str := 'SELECT USERNAME FROM ' || tab
      || ' WHERE sid= :id';
dbms_output.put_line(query_str);
    OPEN cur FOR query_str USING sid;
END ;
/

Commence Example

create table test1(sid number, username varchar2(50));
insert into test1(sid, username) values(123,'abc');
insert into test1(sid, username) values(123,'ddd');
insert into test1(sid, username) values(222,'abc');
commit;
/

 declare
  cur  sys_refcursor ;
  sid number ;
  uName varchar2(50) ;
  begin
  sid := 123;
  dynaQuery('test1',sid, cur);
   LOOP
     FETCH cur INTO uName;
     DBMS_OUTPUT.put_line(uName);
     EXIT WHEN cur%NOTFOUND;
     -- process row here
   END LOOP;
CLOSE CUR;

  end ;

Output:

SELECT USERNAME FROM test1 WHERE sid= :id
abc
ddd
abc
ddd
ddd

EDIT: Added Close CUR that was rightly suggested by @JackPDouglas