Search code examples
oracleplsqloracle11gdatabase-trigger

How I can create a trigger with a derived attribute?


I have a database of a video store, to ask the question that I have exposed, I thought about updating an age attribute that corresponds to the actors, but this doesn't make sense (as I show below in an example)

CREATE TABLE dobs ( dob date, age number(3));
insert into dobs values ((to_date('1999-10-04','yyyy-mm-dd')),NULL);

CREATE OR REPLACE FUNCTION get_age
(
    fnacimiento date
) 
return int 
is edad int;
begin
    select floor(months_between(sysdate,dob)/12) into edad
    from dobs
    where dob=fnacimiento;
    return edad;
end get_age;

CREATE OR REPLACE TRIGGER agec before INSERT OR UPDATE ON dobs
FOR EACH ROW
BEGIN
   :new.age := get_age(:new.dob);
END;

Solution

  • You don't need a function in order to update that column. Even no need to use a SELECT Statement. Just rearrange the trigger as :

    CREATE OR REPLACE TRIGGER agec BEFORE INSERT OR UPDATE ON dobs
    FOR EACH ROW
    BEGIN
       :new.age := floor(months_between(sysdate,:new.dob)/12);
    END;