Oracle - 插入到一个表中的触发器,同时防止插入到另一个表中

时间:2018-04-19 00:59:52

标签: sql oracle plsql triggers

使用触发器我想阻止插入某个表,同时在不同的错误表中插入一行。我很难做到这一点。我曾尝试使用raise_application_error,但这也会阻止插入错误表。

表定义如下 -

防止插入的表:

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)
);

错误表(对于新插入):

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 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
    insert into ReserveError (Err,MID,RID, ErrorDate, errorCode, errorMsg) VALUES (Error_Seq.nextVal, :new.MID, :new.RID, SYSDATE, 'g00001', 'Female guest assigned to male room');
  ELSIF Room_Gender = 'F' AND Guest_Gender = 'M' THEN
    insert into ReserveError (Err,MID,RID, ErrorDate, errorCode, errorMsg) VALUES (Error_Seq.nextVal, :new.MID, :new.RID, SYSDATE, 'g00002', 'Male guest assigned to female room');
  END IF;
  END Gender_Assign_Trigger;
/

1 个答案:

答案 0 :(得分:0)

create or replace procedure sp_reserve_error
(
MID int, RID int, errorCode varchar2, errorMsg varchar2
)
as
pragma autonomous_transaction;
begin
  insert into ReserveError (Err,MID,RID, ErrorDate, errorCode, errorMsg) 
  VALUES (Error_Seq.nextVal, MID, RID, SYSDATE, errorCode, errorMsg);  
  commit;
end;
/


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
    sp_reserve_error(:new.MID, :new.RID, 'g00001', 'Female guest assigned to male room'); 
  ELSIF Room_Gender = 'F' AND Guest_Gender = 'M' THEN
    sp_reserve_error(:new.MID, :new.RID, 'g00002', 'Male guest assigned to female room'); 
  END IF;
  END Gender_Assign_Trigger;
/