如何在Oracle SQL中使用触发器显示AGE?

时间:2017-07-31 09:14:41

标签: sql oracle triggers

我有两个不同的表,我在其中创建了表1

CREATE TABLE  "STUD_PERS" 
   (    "ENROLL" NUMBER NOT NULL ENABLE, 
    "NAME" VARCHAR2(30), 
    "BRANCH" VARCHAR2(30), 
    "YEAR" NUMBER, 
    "DATE0FBIRTH" DATE NOT NULL ENABLE, 
     CONSTRAINT "STUD_PERS_PK" PRIMARY KEY ("ENROLL") ENABLE
   )

Table 1

表2

CREATE TABLE  "SCHO" 
   (    "ENROLL" NUMBER NOT NULL ENABLE, 
    "ANN_INC" NUMBER, 
    "AGE" NUMBER, 
     CONSTRAINT "SCHO_PK" PRIMARY KEY ("ENROLL") ENABLE
   )

Table 2

我想通过使用表1中的DATEOFBIRTH编写一个Trigger来显示表2中的AGE

1 个答案:

答案 0 :(得分:0)

1)当我理解你的问题和评论时,你需要在UPDATE发生时触发,对吧?因此,如果某人更新了table1,那么TRIGGER必须在table2上更新年龄,如果是,则尝试此代码:

---- TRIGGER will UPDATE the data of the column AGE in table2 whenever DATE0FBIRTH column has been UPDATED and COMMITTED:

    CREATE OR REPLACE TRIGGER scho_age 
    AFTER UPDATE OF DATE0FBIRTH 
          ON  STUD_PERS
          REFERENCING OLD AS OLD NEW AS NEW
          FOR EACH ROW
        BEGIN
          UPDATE SCHO SET AGE = (EXTRACT (YEAR FROM SYSDATE) - EXTRACT (YEAR FROM :NEW.DATE0FBIRTH)) WHERE ENROLL= :OLD.ENROLL;
    END;

2)或者如果你只需要显示然后为table1创建一个VIEW并从那里查询AGE而不复制数据:

SELECT (EXTRACT (YEAR FROM SYSDATE) - EXTRACT (YEAR from DATE0FBIRTH)) AGE from table1;