简体   繁体   English

在PL / SQL中添加约束

[英]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 ? 如何在Department表上创建约束,以使经理的年龄始终> 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: 在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) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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