oracle select *来自变量表名

时间:2016-12-06 01:54:26

标签: oracle tablename

ORACLE:到目前为止,我所尝试的一切都没有奏效。我希望在屏幕上显示select * from my_table的结果。在这种情况下,my_table = select table_name from all_tables where owner='ABC' and name like 'ABC%'。表名是一个加号,但列名是必要的。我可以在几秒钟内使用DB2完成此操作,但无法完全转换为Oracle。

我的尝试:

    variable refcur refcursor;
    declare
    my_select     varchar2(64);
    cursor c_tables is
        select table_name
          from all_tables 
         where owner='ABC' and table_name like 'ABC%';
    begin
    for x in c_tables
      loop
         dbms_output.put_line(x.table_name);  
         my_select := 'select * from ' || x.table_name;
         open :refcur for my_select;
      end loop;

   exception
     when no_data_found
     then dbms_output.put_line('Nothing is found');
   end;
   /

variable refcur refcursor; declare my_select varchar2(64); cursor c_tables is select table_name from all_tables where owner='ABC' and table_name like 'ABC%'; begin for x in c_tables loop dbms_output.put_line(x.table_name); my_select := 'select * from ' || x.table_name; open :refcur for my_select; end loop; exception when no_data_found then dbms_output.put_line('Nothing is found'); end; /

在我的所有尝试中,我得到的最好的是桌子不存在 感谢

2 个答案:

答案 0 :(得分:0)

我不知道您是如何登录的,但如果您未以ABC身份登录,则需要将模式与表名一起包含在内,例如

my_select := 'select * from ' || x.owner || '.' || x.table_name;

此外,打开光标不会从中获取任何内容,或在任何地方显示数据。您需要添加逻辑以从光标获取数据,显示数据并关闭光标。并且由于表名没有修复,数据库无法提前告诉您行的样子,因此您需要熟悉DBMS_SQL包,该包用于处理动态SQL,如此

祝你好运。

答案 1 :(得分:0)

您可以在下面举例说明:

create or replace procedure app_test(v_tab varchar2) is
  type cur_type is ref cursor;
  my_cur   cur_type;
  v_name   varchar2(20);
  dyna_sql varchar2(4000);
begin
  dyna_sql := 'select username from ' || v_tab || ' where rownum=1';
  open my_cur for dyna_sql;
  fetch my_cur
    into v_name;
  while my_cur%found LOOP
    fetch my_cur
      into v_name;
    DBMS_output.put_line(v_name);
  end loop;
  close my_cur;
end app_test;