使用触发器约束列值

时间:2015-05-07 23:59:17

标签: sql oracle oracle11g triggers

我正在尝试使用trigger(按照Bohemian建议的here)来约束我的表格中会出现多少yes/no。对于yes列中的每个唯一商品,我在isTeamLead列中最多只需要一个project,但根据需要可以包含nono。对于no1,似乎我能做的最好就是使用一种解决方法,我可以使用no2no3yes等等。我的代码成功插入了{ {1}}行,但会在no行上抛出错误。

DROP TABLE team CASCADE CONSTRAINTS PURGE ;
create table team (
  name varchar2(10) NOT NULL UNIQUE,
  project varchar2(10),
  isTeamLead char(10) check (isTeamLead IN ('No', 'Yes'))
);

create unique index only_one_yes_per_project on team(project, isTeamLead);

DROP SEQUENCE test1_seq; 
create SEQUENCE test1_seq
START WITH 1
INCREMENT BY 1;

set define off;
set serveroutput on format wrapped;
CREATE OR REPLACE TRIGGER insert_yesno
  BEFORE INSERT ON team
  FOR EACH ROW
BEGIN
  IF (:new.isTeamLead = 'No') THEN 
    DBMS_OUTPUT.put_line(:new.isTeamLead);
    :new.isTeamLead := CONCAT('No', test1_seq.nextval);
    DBMS_OUTPUT.put_line(:new.isTeamLead);
    INSERT INTO team VALUES
      (:new.name, :new.project, :new.isTeamLead);
  END IF; 
END insert_yesno;
/

insert into team values ('member1', 'project1', 'Yes');
insert into team values ('member2', 'project1', 'No');
insert into team values ('member3', 'project1', 'No');
insert into team values ('member4', 'project2', 'No');
insert into team values ('member5', 'project2', 'Yes');
insert into team values ('member6', 'project2', 'No');

select * from team;

以下是错误报告的快照:

Error starting at line : 244 in command -
insert into team values ('member6', 'project2', 'No')
Error report -
SQL Error: ORA-02290: check constraint (SEDEH.SYS_C0012563) violated
ORA-06512: at "SEDEH.INSERT_YESNO", line 6
ORA-04088: error during execution of trigger 'SEDEH.INSERT_YESNO'
02290. 00000 -  "check constraint (%s.%s) violated"
*Cause:    The values being inserted do not satisfy the named check

如果有任何想法,请告诉我。谢谢。

运行Oracle Database 11g企业版11.2.0.1.0版

1 个答案:

答案 0 :(得分:2)

为什么不添加一个独特的基于函数的索引?以下内容应该将列限制为每个项目只有一个团队负责人:

create unique index idx_team_isTeamLead_yes on
    team(case when isTeamLead = 'yes' then project else NULL end);

这利用了Oracle忽略所有索引列为NULL的行。