Dead Programmer
Dead Programmer

Reputation: 12575

Passing the tablename to the cursor

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.

Upvotes: 1

Views: 11557

Answers (2)

Harrison
Harrison

Reputation: 9090

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

Upvotes: 5

user533832
user533832

Reputation:

You can't use dynamic sql with a cursor - you might be able to do what you want using a ref cursor. See here for example

Upvotes: 4

Related Questions