【问题标题】:Oracle Procedure to insert all records from one staging table into main tableOracle过程将一个临时表中的所有记录插入主表
【发布时间】:2021-12-27 10:16:39
【问题描述】:

我写了Stored Procedure (SP),其中在 SP 内部,2 个 SP 分开用于从表中插入 2 个。两个表在每个临时表和主表中都包含超过 25 列。以下是查询-

create or replace procedure sp_main as

 procedure tbl1_ld as 
  cursor c1 is select * from tmp1;
  type t_rec1 is table of c1%rowtype;
  v_rec1 t_rec1;
 begin
  open c1;
  loop
   fetch c1 bulk collect into v_rec1 limit 1000;
   exit when v_rec1.count=0;
   insert into tbl1 values v_rec1;
  end loop;
 end tbl1_ld;

 procedure tbl2_ld as 
  cursor c2 is select * from tmp2;
  type t_rec2 is table of c2%rowtype;
  v_rec2 t_rec2;
 begin
  open c2;
  loop
   fetch c2 bulk collect into v_rec2 limit 1000;
   exit when v_rec2.count=0;
   insert into tbl2 values v_rec2;
  end loop;
 end tbl2_ld;

begin
 null;
end sp_main;
/

我使用EXECUTE IMMEDIATE 'insert into tbl1 select * from tmp1'; 在两个SP 中插入tbl1_ld & tbl2_ld 而不是使用cursor,SP 已编译但没有插入记录。

【问题讨论】:

    标签: sql oracle stored-procedures plsql


    【解决方案1】:

    嗯,您实际上并没有运行任何这些程序。代码的最后几行应该是

      <snip>
      end tbl2_ld;
    
    begin
      tbl1_ld;      --> this
      tbl2_ld       --> this
    end sp_main;
    /
    

    另一方面,我更喜欢避免使用insert into ... select * from,因为当您修改表的描述并且不修复使用这些表的代码时,它只会失败。

    是的,我知道 - 为所有 25 列命名只是 无聊,但是 - 在我看来 - 这是值得的。因此,我只想

    begin
      insert into tbl1 (id, name, address, phone, ... all 25 columns)
      select id, name, address, phone, ... all 25 columns
      from tmp1;
    
      insert into tbl2 (id, name, address, phone, ... all 25 columns)
      select id, name, address, phone, ... all 25 columns
      from tmp2;
    end;
    

    换句话说,没有游标、类型、循环……什么都没有。可能是纯 SQL(即没有 PL/SQL)。如果要限制插入的行数,请使用例如... where rownum &lt;= 1000(如果这就是您使用 limit 子句的原因)。


    关于你提到的动态 SQL (execute immediate):为什么你会使用它?你写的代码没有什么动态的。

    【讨论】:

    • “因为当你修改表的描述并且不修复使用这些表的代码时它只是喜欢失败”。另一种看待事物的方式是,这是一个特性而不是一个错误。有时我们需要表结构保持同步;在仓库中,我们可能有临时临时表和永久存档表,它们应该具有匹配的投影。在这种情况下,select * from 的使用就像金丝雀一样提醒我们更改两个表。我承认这不是一个常见的用例,但它是我遇到的一个,看起来它可能适合 Seeker 的场景。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 2014-08-06
    • 2012-03-23
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多