【问题标题】:Inserting multiple records from a trigger in oracle从oracle中的触发器插入多条记录
【发布时间】:2012-05-24 12:47:11
【问题描述】:

我创建了一个触发器,以便在职位更新时插入员工 ID。 在某些情况下,一个职位有很多员工,因此触发器无法插入所有员工(只有 1 个)。我需要所有员工 ID

任何人都可以帮我处理这段代码吗?

问候

create or replace trigger postn_updt
after update on postn
for each row

declare 

cursor m is 
select u.login
from user u,
party_per s
where u.row_id=s.person_id 
and s.party_id=:new.row_id;

rownum varchar2(10);

begin
if updating ('postn_type_cd') then
open mult;
fetch mult into rownum;

insert into test123
(employee_number,type,request_date,remarks)
values
(( rownum,
'Updated',sysdate,''
);
close m;
end if;
end;

【问题讨论】:

  • 你要么需要一个循环,要么需要某种形式的“INSERT...SELECT”语句。
  • ROWNUM 是 SQL 中的关键字:这会使您的代码不标准(因此令人困惑),因为您的查询中的 rownum 没有其预期的行为。
  • @VincentMalgrat 在这个例子中,ROWNUM 是一个变量......不是关键字
  • @ShoeLace 使用与非常常见的标准 SQL 函数共享其名称的变量通常是一个坏主意。它是shadowing 的一种形式,这会使人类读者感到困惑。好的代码应该是人机可读的。
  • 同意..我只是想指出在这种情况下它不会引起问题

标签: oracle plsql triggers cursor


【解决方案1】:

触发器 != 应用程序代码

如果您像这样将应用程序代码嵌入到触发器中,那么维护和调试将非常糟糕,并且您总是会遇到由于变异表错误而导致基于触发器的方法无法工作的情况。

最好只为审计和其他非应用程序活动保留触发器,并将这种逻辑放在应用程序本身中。

【讨论】:

    【解决方案2】:

    要插入多行,您需要一个 LOOP 或某种形式的“INSERT...SELECT”语句。

    例如。

    create or replace trigger postn_updt
    after update on postn
    for each row
    
    declare 
    
    cursor m is 
    select u.login
    from user u,
    party_per s
    where u.row_id=s.person_id 
    and s.party_id=:new.row_id;
    
    begin
    if updating ('postn_type_cd') then
    
      for mult_rec in  m LOOP
    
        insert into test123
        (employee_number,type,request_date,remarks)
        values
        (( mult_rec.login,
        'Updated',sysdate,''
        );
      END LOOP;
    
    end if;
    end;
    

    create or replace trigger postn_updt
    after update on postn
    for each row
    
    declare 
    begin
    if updating ('postn_type_cd') then
    
        insert into test123
        (employee_number,type,request_date,remarks)
        select u.login ,'Updated',sysdate,''
        from user u,
            party_per s
        where u.row_id=s.person_id 
        and s.party_id=:new.row_id;
    
    end if;
    end;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 2013-06-11
      • 2020-04-12
      相关资源
      最近更新 更多