添加约束在PL/SQL
问题描述:
我有两个表:添加约束在PL/SQL
Employee(eid, ename, age..)
Department(deptid, dname, managerid..) //manager id references eid
我如何创建部门表的约束,使得经理人的年龄总是> 25?
答
约束不能包含子查询,因此如果要在数据库级别实施此业务规则,则需要触发器。像这样的东西。
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;
顺便说一句不要在表中存储年龄。每天都不一样。
答
在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));
,当然,这触发不会拿起如果员工的年龄随后修正为少于25。 –