PL / SQL ORACLE:删除时触发更新

时间:2017-11-25 00:14:44

标签: sql database oracle plsql triggers

我试图创建一个触发器来增加预订值,并在表ticket_price中插入新记录时减少可用值。如果删除记录,我希望它减少预订值并增加可用值。

虽然我能够成功地使INSERT的触发器工作,但是我无法在删除记录时更新值。我是每当我尝试删除记录时出现的错误

ORA-01403: no data found
ORA-06512: at "K.CAL", line 6
ORA-04088: error during execution of trigger 'K.CAL'

为了澄清,我正在更新另一个表中的值,而不是我要删除的同一个表!

以下是我的触发器代码:

CREATE OR REPLACE TRIGGER cal 
   BEFORE INSERT OR DELETE ON TICKET_PRICE FOR EACH ROW
DECLARE
    V_TICKET TICKET_PRICE.TICKETPRICE%TYPE;
    V_BOOKED FLIGHTSEAT.BOOKED_SEATS%TYPE;
    V_AVAILABLE FLIGHTSEAT.AVAILABLE_SEATS%TYPE;
BEGIN
    SELECT BOOKED_SEATS,AVAILABLE_SEATS 
    INTO V_BOOKED,V_AVAILABLE 
    FROM FLIGHTSEAT 
    WHERE SEAT_ID=:NEW.SEAT_ID;
    IF INSERTING THEN 
        V_BOOKED:=V_BOOKED+1;
        V_AVAILABLE:=V_AVAILABLE-1;
        UPDATE FLIGHTSEAT 
        SET BOOKED_SEATS=V_BOOKED, AVAILABLE_SEATS=V_AVAILABLE
        WHERE SEAT_ID=:NEW.SEAT_ID;
    ELSIF DELETING THEN 
        V_BOOKED:=V_BOOKED-1;
        V_AVAILABLE:=V_AVAILABLE+1;
        UPDATE FLIGHTSEAT 
        SET BOOKED_SEATS=V_BOOKED, AVAILABLE_SEATS=V_AVAILABLE 
        WHERE SEAT_ID=1;
    END IF;
END;

1 个答案:

答案 0 :(得分:1)

您已正确推测:删除更新时无法使用new.seat。但是它既不适用于选择,你知道sea_id = 1是否需要更新?有关已删除行数据的参考,请使用:Old.column name;在这种情况下使用:old_seat_id用于选择和更新。

但你根本不需要选择。注意:此外,您有一个隐含的假设,即seat_id是唯一的。我会在下面接受。

create or replace trigger cal 
    before insert or delete on ticket_price 
    for each row
declare
v_seat_id         flightseat.seat_id%type;          
v_booked          flightseat.booked_seats%type;     

begin
    if INSERTING then 
        v_booked  := 1;
        v_seat_id := :new.seat_id; 
    else
        v_booked  := -1;
        v_seat_id := :old.seat_id; 
    end if;

    update flightseat 
       set booked_seats=booked_seats+v_booked
         , available_seats=available_seats-v_booked 
     where seat_id = v_seat_id;

end;