After a trigger is executed on one table, is it possible to display the values of a column from another table? (PL/SQL)

时间:2016-04-21 22:16:10

标签: plsql triggers

I have a trigger that will execute when a table is updated. The trigger updates another table. I'd like to display the changes of the second table.

This is the code that I have:

create or replace trigger update_club_fee
after update of fee on sporting_clubs
for each row

begin

update club_membership set amount = (duration*:new.fee) where :old.club_id = :new.club_id;

dbms_output.put_line('Customer id is: '||:new.customer_id);
dbms_output.put_line('Previous amount was '||:old.amount);
dbms_output.put_line('New amount is '||:new.amount);
end;

2 个答案:

答案 0 :(得分:0)

我认为触发器不是合适的技术解决方案。捕获俱乐部成员资格更改的UI代码应将更改传播到子表并提供任何报告。

但如果你真的需要使用触发器,那就不可能了:

  1. 你不能在CLUB_MEMBERSHIP上引用:old和:new - 这些是 仅与触发器拥有表相关的记录 (本例中为SPORTING_CLUBS)。 :old.amount无法解析
  2. SPORTING_CLUBS中的一行更新可能会导致许多行 在CLUB_MEMBERSHIP更新(每个俱乐部有一个以上的成员, 对?)。我认为你想知道每一行
  3. 我会写一个接受club_id和费用的程序。这将更新CLUB_MEMBERSHIP中的所有相关行,然后还将报告更新的行。然后从触发器调用此过程。

    但是,请不要使用触发器。

答案 1 :(得分:0)

我同意Christian Palmer关于触发器的使用,但有时触发器是客户的要求(是的,我有一个客户的要求!),你必须这样做。此外,并不总是可以在触发器中添加过程调用(如果过程引用事务中修改的任何表,则会调用它时出错)。

在这些情况下,可能的解决方案如下,使用游标循环所有成员:

CREATE OR REPLACE TRIGGER UPDATE_CLUB_FEE
AFTER UPDATE OF FEE ON SPORTING_CLUBS
FOR EACH ROW

BEGIN

    FOR c IN (
        SELECT *
        FROM club_membership
        WHERE club_id = :old.club_id
    ) LOOP
        dbms_output.put_line('Customer id is: '     || c.customer_id);
        dbms_output.put_line('Previous amount was ' || c.amount);
        dbms_output.put_line('New amount is '       || c.duration * :new.fee);
    END LOOP;

    UPDATE club_membership 
    SET amount = duration * :new.fee
    WHERE club_id = :old.club_id;

END;