PL / SQL迭代所有模式并对所有模式运行相同的查询

时间:2012-08-22 19:14:21

标签: oracle function plsql

我有各种Oracle数据库,例如ONE.db TWO.db THIRD.db等,我想在ONE.db上成功运行一个SELECT,例如,SELECT * FROM CUSTOMERS等,然后得到每个结果数据库。我怎么能用PL / SQL做到这一点? (没有数据库链接或工具等)

1 个答案:

答案 0 :(得分:3)

假设您正在讨论模式,而不是单独的数据库实例,并假设所有CUSTOMERS表的结构完全相同(包括列顺序),您可以以对所有表具有SELECT访问权限的用户身份登录,然后:

SELECT 'ONE' owner, c.* FROM one.customers c
UNION ALL
SELECT 'TWO' owner, c.* FROM two.customers c
UNION ALL
SELECT 'THIRD' owner, c.* FROM third.customers c
;

您是否需要第一列“所有者”取决于您。

如果要在运行时使用PL / SQL生成上述语句,可以执行以下操作:

DECLARE
  qry VARCHAR2(32767);
  rc sys_refcursor;
BEGIN
  FOR r IN (SELECT owner, table_name
            FROM all_tables
            WHERE table_name = 'CUSTOMERS') LOOP
    IF qry IS NOT NULL THEN
      qry := qry || ' UNION ALL ';
    END IF;
    qry := qry || 'SELECT '''
               || r.owner
               || ''' owner, c.* FROM '
               || r.owner
               || '.customers c';
  END LOOP;
  OPEN rc FOR qry;
  -- fetch from the ref cursor and do whatever you want with the records
END;