简体   繁体   中英

Adding constraint in PL/SQL

I have two tables:

Employee(eid, ename, age..)
Department(deptid, dname, managerid..) //manager id references eid

How can I create a constraint on Department table such that manager's age is always > 25 ?

A constraint cannot contain a subquery so a trigger is needed if you want to enforce this business rule on database level. Something like this.

create or replace trigger dep_briu_trg
  before insert or update on department  
  for each row
declare
  l_age employee.age%type;   

    begin
       select age
       into l_age
       from empoyee
       where id=:new.managerid;

       if l_age<=25 then
        raise application_error(-20000,'Manager is to young');
       end if;
    exception
       when no_data_found then
        raise application_error(-20000,'Manager not found');
    end;

BTW Never store age in a table. It's different every day.

In Oracle 11g, you could use a virtual column to be the target of a foreign key:

CREATE TABLE emp (eid NUMBER PRIMARY KEY,
                  age NUMBER NOT NULL,
                  eligible_mgr_eid AS (CASE WHEN age > 25 THEN eid ELSE NULL END) UNIQUE
                 );

CREATE TABLE dept (did NUMBER PRIMARY KEY,
                   mgr_id NUMBER NOT NULL REFERENCES emp (eligible_mgr_eid) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM