Calculating age from birthday with oracle plsql trigger and insert the age in table

前端 未结 3 1694
小蘑菇
小蘑菇 2020-12-21 06:34

i have a table

dates
(dob date,
age number(4)
);

I will insert a date of birth and a trigger will calculate the age and insert that age in

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-21 07:01

    If you want AGE to be available from the database there are two options:

    1. Define a view which contains the age computation, or
    2. Define a virtual column which does the same

    To define such a view:

    CREATE OR REPLACE VIEW DATES_VIEW
      AS SELECT DOB,
                FLOOR(MONTHS_BETWEEN(SYSDATE, DOB) / 12) AS AGE
            FROM DATES
    

    The problem with this is that you have to remember that you SELECT from DATES_VIEW, but need to update DATES, which is mentally messy. IMO adding a virtual column to the table is cleaner:

    CREATE TABLE DATES
      (DOB      DATE,
       AGE      GENERATED ALWAYS AS (FLOOR(MONTHS_BETWEEN(SYSDATE, DOB) / 12)) VIRTUAL);
    

    Note that virtual columns cannot be updated.

    Either method helps to ensure that AGE will always be consistent.

    Share and enjoy.

提交回复
热议问题