Oracle - 使用触发器删除行

时间:2018-04-19 20:47:08

标签: sql oracle plsql database-trigger

当对Condo_assign进行插入时,我使用多个触发器将条目添加到reserveError表以指示错误是什么。登录reserveError后,我现在尝试使用另一个触发器删除导致问题的condo_assign记录。基本上,错误的插入应记录在ReserveError中并从Condo_assign中删除。问题是,虽然我的删除触发器编译并且没有引起任何问题,但它似乎没有做任何事情。当我select * from condo_assign时,错误的条目仍在那里。

Condo_Assign table:

CREATE TABLE Condo_Assign (
  MID INT
, RID VARCHAR2(3)
, CONSTRAINT Condo_Assign Primary Key (MID,RID)
, CONSTRAINT MID_Assign_FK Foreign Key (MID) references SkiClub (MID)
, CONSTRAINT RID_Assign_FK Foreign Key (RID) references Condo_Reservation (RID)
);

reserveError表:

CREATE TABLE ReserveError (
Err INT PRIMARY KEY
, MID INT
, RID VARCHAR2(3)
, errorDate DATE
, errorCode VARCHAR2(6)
, errorMsg VARCHAR2(60)
, CONSTRAINT Error_MID_FK FOREIGN KEY (MID) REFERENCES SkiClub
, CONSTRAINT Error_RID_FK FOREIGN KEY (RID) REFERENCES Condo_Reservation
);

导致触发的程序:

CREATE OR REPLACE Procedure addCondo_Assign
(
inMID in Condo_Assign.MID%type
, inRID in Condo_Assign.RID%type
, inPaymentDate in Payment.PaymentDate%type
, inPayment in Payment.Payment%type
)
is
begin
insert into Condo_Assign (MID,RID) values (inMid,inRid);
IF inPayment >= 50 then 
    insert into Payment (MID,RID,PaymentDate,Payment) values (inMID,inRID,inPaymentDate,inPayment);
ELSE
    raise_application_error(-20088,'Deposit less than 50');
end if;

exception
    when others then
    raise_application_error(-20005,'Cannot add to entry to Condo_Assign Table.');
end addCondo_Assign;
/

写入ReserveError表的触发器

-- Trigger to prevent gender mismatchs in room assignment
CREATE OR REPLACE TRIGGER Gender_Assign_Trigger
BEFORE INSERT ON Condo_Assign
FOR EACH ROW
DECLARE
Room_Gender Char(1);
Guest_Gender Char(1);
BEGIN
SELECT Gender 
    INTO Room_Gender
    From Condo_Reservation
    WHERE RID = :new.RID;
SELECT Gender
    INTO Guest_Gender
    FROM SkiClub
    WHERE MID = :new.MID;       
IF Room_Gender = 'M' AND Guest_Gender = 'F' THEN
    addReserveError(:new.MID,:new.RID,SYSDATE,'g00001','Female guest assigned to male room');
ELSIF Room_Gender = 'F' AND Guest_Gender = 'M' THEN
    addReserveError(:new.MID,:new.RID,SYSDATE,'g00002','Male guest assigned to female room');
END IF;
END Gender_Assign_Trigger;
/

应该从condo_assign删除条目的触发器:

CREATE OR REPLACE TRIGGER Remove_errors_trigger
after Insert on ReserveError
FOR EACH ROW
BEGIN
  DELETE FROM Condo_Assign
  WHERE MID = :new.MID and RID = :new.RID;
END remove_errors_trigger;
/

1 个答案:

答案 0 :(得分:1)

整个过程在插入触发器中启动。

尝试删除记录的代码不会删除任何内容,因为尚未插入记录。删除代码被解除时无需删除任何内容。

通常,检入触发器会阻止插入引发异常的错误数据。插入数据的代码必须处理异常。

但是你已经有一个处理插入的过程。它甚至会对存款进行检查。为什么不在那里处理性别检查?