Oracle

“觸發”觸發器以填充非 NULL 列?

  • September 17, 2019

目前正在研究我的 SQL 書。問題是,根據 ENROLLMENT 表創建一個觸發器。觸發器應該在 INSERT 語句之前“觸發”。觸發器將填充所有非 NULL 列和具有外鍵約束的列。

CREATE OR REPLACE TRIGGER triggerOne
BEFORE INSERT ON ENROLLMENT
FOR EACH ROW
BEGIN
 --loop to get all of our columns that are are checked to be not NULL
 FOR i in (SELECT STUDENT_ID ,SECTION_ID ,ENROLL_DATE ,FINAL_GRADE ,CREATED_BY ,CREATED_DATE ,MODIFIED_BY , MODIFIED_DATE  
           FROM ENROLLMENT 
           WHERE created_by || created_date || enroll_date || final_grade || modified_by || modified_date || section_id || student_id IS NOT NULL) 
 --loop for CHECK constraints from ENROLLMENT table
 LOOP
   IF (CHECK(:NEW.SECTION_ID = ENR_SECT_FK) AND CHECK(:NEW.STUDENT_ID = ENR_STU_FK)) THEN 
     INSERT INTO ENROLLMENT(9,9,'30-JAN-99',9,'9','09-SEP-99','9','01-JAN-00');
   END IF;
 END LOOP;
END;

我在第 9 行遇到錯誤

錯誤(9,5):PLS-00103:在預期以下情況之一時遇到符號“CHECK”:(-+ case mod new not null continue avg count current exists max min prior sql stddev sum variance execute forall merge time timestamp interval日期管

我們有一個 ENROLLMENT 表,其中包含非 NULL 列的約束和約束 ENR-SECT_FK 和 ENR_STU_FK 作為外鍵約束。

不知道我在哪裡出錯了……要重新閱讀本章,但任何幫助將不勝感激!

如果要為 NULLable 列設置值,則只需設置這些值,如下所示:

CREATE OR REPLACE TRIGGER enrollment_bi
BEFORE INSERT ON ENROLLMENT
FOR EACH ROW
BEGIN
 IF :NEW.STUDENT_ID    IS NULL THEN
   :NEW.STUDENT_ID    := 9;
 END IF;
 IF :NEW.SECTION_ID    IS NULL THEN
   :NEW.SECTION_ID    := 9;
 END IF;
 IF :NEW.ENROLL_DATE   IS NULL THEN
   :NEW.ENROLL_DATE   := TO_DATE('30-JAN-99','DD-MON-YY');
 END IF;
 IF :NEW.FINAL_GRADE   IS NULL THEN
   :NEW.FINAL_GRADE   := 9;
 END IF;
 IF :NEW.CREATED_BY    IS NULL THEN
   :NEW.CREATED_BY    := '9';
 END IF;
 IF :NEW.CREATED_DATE  IS NULL THEN
   :NEW.CREATED_DATE  := TO_DATE('09-SEP-99','DD-MON-YY');
 END IF;
 IF :NEW.MODIFIED_BY   IS NULL THEN
   :NEW.MODIFIED_BY   := '9';
 END IF;
 IF :NEW.MODIFIED_DATE IS NULL THEN
   :NEW.MODIFIED_DATE := TO_DATE('01-JAN-00','DD-MON-YY');
 END IF;
END;
/

之前不需要閱讀表格(當然不是在 FOR 循環中)——這實際上是被禁止的。觸發器針對任何 SQL 語句修改的每一行執行,並為您提供呼叫它的操作的上下文:變數:OLD包含列的先前值 (for UPDATEand DELETES) 和:NEW新值 (for UPDATEand INSERT)。因此,您只需要更改其中的值(:NEW如果其中任何一個是NULL.

再說一次,您根本不需要觸發器:只需在創建表時將您想要的值指定為預設值:

CREATE TABLE ENROLLMENTS (
 STUDENT_ID    NUMBER        DEFAULT 9,
 SECTION_ID    NUMBER        DEFAULT 9,
 ENROLL_DATE   DATE          DEFAULT TO_DATE('30-JAN-99','DD-MON-YY'),
 FINAL_GRADE   NUMBER        DEFAULT 9,
 CREATED_BY    VARCHAR2(20)  DEFAULT '9',
 CREATED_DATE  DATE          DEFAULT TO_DATE('09-SEP-99','DD-MON-YY'),
 MODIFIED_BY   VARCHAR2(20)  DEFAULT '9', 
 MODIFIED_DATE DATE          DEFAULT TO_DATE('01-JAN-00','DD-MON-YY')
);

我在這裡猜測數據類型 - 你可能有不同的數據類型。

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