【问题标题】:Oracle dynamic Schema in for loopfor循环中的Oracle动态模式
【发布时间】:2018-06-19 17:33:44
【问题描述】:

如何在 for 循环中使用动态 sql 语句? 我有一个来自外部循环的变量 i.owner 代表 Schema。

for j in (select * from <schema>.<table>)
loop
    begin
        null;
    exception when others then DBMS_OUTPUT.PUT_LINE('error');
    end;
end loop;

游标会导致类似的问题。

【问题讨论】:

  • 表名 - 或者至少是表结构,或者您查询的列及其数据类型 - 是固定的,还是每个 i 都可能改变?
  • 这实际上是固定的,我也只需要 1 个 varchar2 列

标签: oracle for-loop dynamic plsql schema


【解决方案1】:

您不能在 cursor-for 循环中使用动态 SQL。您必须对集合进行批量查询,或者可能更有用地使用open for, fetch and close pattern,例如:

declare
  c sys_refcursor;
begin
  for i in (<however you get the owner/table_name now>)
  loop

    open c for 'select * from ' || i.owner || '.' || i.table_name;
    loop
      begin
        fetch c into ...;
        exit when c%notfound;
      exception when others then DBMS_OUTPUT.PUT_LINE('error');
      end;
    end loop; -- j
    close c;
  end loop; -- i
end;
/

问题在于... 部分 - 即您获取的内容。如果表结构,或者至少您正在查询的列,每次在i 循环中都是相同的,那么您可以定义单独的标量变量以将每一列提取到,或者根据%rowtype 定义一个记录变量其中一个表(如果它们都相同,并且您始终知道存在一个表,并且您正在使用select *),或者定义一条记录,其中包含您正在获取的内容的字段。

如果结构可以变化,那么您必须查看dbms_sql 包。

如果表名始终相同,并且不是来自您的 i 循环,则可以稍微简化为:

    open c for 'select * from ' || i.owner || '.<table_name>';

【讨论】:

  • 谢谢 :) 与“'select CR from ' || i.owner || '.MIG_TAB where status = 0 group by CR'”和“将 c 提取到 CR”配合得很好
猜你喜欢
  • 2018-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 2020-06-26
  • 1970-01-01
  • 2016-08-19
  • 1970-01-01
相关资源
最近更新 更多