PL / SQL在多个数据库上查询表

时间:2013-08-15 16:19:19

标签: database plsql cursor

我有点卡住了。我有一个包含数据库名称列表的表。我想查询数据库名称,然后查询此数据库以从其“systemtable”返回详细信息。 我一直在尝试使用2个游标,但它不适合我(只是找不到语法),任何指针/帮助将不胜感激。

declare

  cursor c_dbNames is select dbname
                  from DB_INFO order by name ASC;
  v_curr_dbname VARCHAR2(60);

begin

  open c_dbNames;
  LOOP
      FETCH c_dbNames into v_curr_dbname;
      EXIT WHEN c_dbnames%NOTFOUND;
      begin
          cursor c_dbDetails is select value
                    from SYSTEMTABLE@'||v_curr_dbname||' order by name ASC;
          v_curr_detail  VARCHAR2(60);

          open c_dbDetails;
            LOOP
                FETCH c_dbDetails into v_curr_detail;
                EXIT WHEN c_dbDetails%NOTFOUND;
                htp.p('<tr><th>'||v_curr_detail||'</th></tr>');
            END LOOP;
          close c_dbDetails;
      end;
  END LOOP;
  close c_dbnames;

end;

2 个答案:

答案 0 :(得分:0)

你必须稍微调整一下:

declare
    cursor c_dbNames is
        select 'dual' dbname from dual union all
        select 'dual' dbname from dual union all
        select 'dual' dbname from dual
        order by dbname ASC;

    v_curr_dbname VARCHAR2(60);
begin
    open c_dbNames;
    LOOP
        FETCH c_dbNames into v_curr_dbname;
        EXIT WHEN c_dbnames%NOTFOUND;

        DECLARE
            v_cursor        integer;
            v_rows          integer;
            v_curr_detail   char(20);
        begin
            v_cursor := DBMS_SQL.OPEN_CURSOR;
            DBMS_SQL.PARSE(v_cursor, 'select ''c_dbDetails'' c_dbDetails FROM ' || v_curr_dbname, DBMS_SQL.NATIVE);
            DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_curr_detail, 20);
            v_rows := DBMS_SQL.EXECUTE(v_cursor);

            loop
                if DBMS_SQL.FETCH_ROWS(v_cursor) = 0 then
                    exit;
                end if;

                DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_curr_detail);
                DBMS_OUTPUT.PUT_LINE('<tr><th>' || v_curr_detail ||'</th></tr>');
            end loop;

            DBMS_SQL.CLOSE_CURSOR(v_cursor);
        end;
    END LOOP;
    close c_dbnames;
end;

答案 1 :(得分:0)

declare
  cursor databases_c is
    -- put your database links here
    select 'XXX' as dbname from dual union
    select 'YYY' from dual;
  v_global_name varchar2(4000);
begin
  for v_dbname in databases_c loop
    -- query the database details
    execute immediate
      'select global_name from global_name@' || v_dbname.dbname
      into v_global_name;
    dbms_output.put_line(v_global_name);
  end loop;
end;
/

<强>输出:

SQL> @so27.sql
XXX
YYY

PL/SQL procedure successfully completed.

SQL>