我有两张桌子:
Employee(eid, ename, age..)
Department(deptid, dname, managerid..) //manager id references eid
如何在Department表上创建约束,使得经理的年龄始终为> 25?
答案 0 :(得分:7)
约束不能包含子查询,因此如果要在数据库级别强制执行此业务规则,则需要触发器。这样的事情。
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切勿将年龄存放在餐桌上。它每天都不同。
答案 1 :(得分:7)
在Oracle 11g中,您可以使用虚拟列作为外键的目标:
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) );