Trigger

PLSQL:在插入觸發器之前

  • March 26, 2013

我正在嘗試編寫我的第一個觸發語句。我正在嘗試創建一個觸發器,該觸發器執行 SELECT 以獲取 LOCO_CLASS 的 MAX_TOW_WEIGHT,然後將該重量與 TRAIN_WEIGHT 進行比較。如果比較失敗(即 TRAIN_WEIGHT > MAX_TOW_WEIGHT),則程式碼將需要引髮使用者定義的異常,需要編寫執行 INSERT 或 UPDATE 的程式碼來處理該異常。我做了以下這很可能是錯誤的,儘管它是一種嘗試:

CREATE TRIGGER LOCOWEIGHT 
BEFORE INSERT
ON Locomotive_Class
REFERENCING NEW AS New
FOR EACH ROW
  BEGIN
     SELECT Train_Weight FROM locomotive
  IF (MAX_TARE_WEIGHT > MAX_TOW_WEIGHT) THEN
      RAISE cError;    
EXCEPTION
WHEN cError THEN
     RAISE_APPLICATION_EXCEPTION('Train weight has exceeded max tow weight');
END;

供參考的表格:

CREATE TABLE Locomotive
(Loco_No integer PRIMARY KEY,
 Serial_No integer UNIQUE,
 Loco_Class_No integer
   REFERENCES Locomotive_Class(Loco_Class_No),
 Loco_name varchar2(20));


CREATE TABLE Locomotive_Class
(Loco_Class_No integer PRIMARY KEY,
 Max_Tow_Weight float NOT NULL,
 Loco_Class_Len float NOT NULL);

幾件事。

1)您的觸發器看起來不正確-我認為您需要將觸發器放在locomotive桌子上,而不是locamotive_class桌子上,並且讓新插入/更新的火車將其最大重量與班級的最大重量進行檢查。

  1. 中沒有train_weightlocomotive table

假設上述情況屬實,這是您需要的觸發程式碼:

CREATE OR REPLACE TRIGGER LOCOWEIGHT 
BEFORE INSERT OR UPDATE ON locomotive
REFERENCING NEW AS New
FOR EACH ROW
DECLARE
 MAX_WEIGHT NUMBER;
BEGIN
 SELECT max_tow_weight INTO MAX_WEIGHT
 FROM locomotive_class
 WHERE loco_class_no = :new.loco_class_no;

  IF :new.train_weight > MAX_WEIGHT THEN
      RAISE_APPLICATION_ERROR(-20000,'Train weight has exceeded max tow weight');
 END IF;
END;

隨著:

alter table locomotive add ( train_weight number ) ; 

引用自:https://dba.stackexchange.com/questions/37582