简体   繁体   中英

PL/SQL: Can I use procedure inputs directly in the select statement?

I was trying to refactor a piece of code. We do a similar select on a table and a view and I wanted to export the select in a procedure and use the table name as an input parameter. So for example:

procedure show_table (
  i_table_name varchar2
)
is
begin
  for c in (
    select *
    from i_table_name
  ) loop
    ...
  end loop;
end;

But PL/SQL thinks i_table_name is a literal name (throws PL/SQL: ORA-00942: table or view does not exist). Is there a way to evaluate the contents of the variable? I guess I can do an execute immediate but I would rather not :)

Cheers.

One possible approach is to use a ref cursor (this assumes that your view has exactly the same columns as the table):

create table test_tab(pk number, value varchar2(30));
insert into test_tab values (1, 'hello');
create view test_view as select pk, value || '_view' as value from test_tab;

declare
  procedure show_table(i_table_name varchar2) is
    cur sys_refcursor;  
    rec test_tab%rowtype;
  begin
    open cur for 'select * from ' || i_table_name;
    loop
      fetch cur into rec;
      exit when cur%notfound;
      dbms_output.put_line(rec.pk ||' ' || rec.value);
    end loop;
  end;
begin
  show_table('TEST_TAB');
  show_table('TEST_VIEW');
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM