2015-05-07 52 views
0

我正在尝试使用trigger(如Bohemian建议的here)来约束我的表中将出现多少个yes/no。我想在project列中的每个唯一项目的isTeamLead列中最多有一个yes列,但可以根据需要具有尽可能多的no。对于no,似乎我可以做的最好的方法是使用解决方法,我可以使用类似于no1,no2,no3等的代码。我的代码成功插入了yes行,但在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数据库11g企业版发布11.2.0.1.0

+0

检查约束允许哪些值?你试图插入'否' - 如果检查约束设置为允许'是'和'否',那么它将不允许'否'。 –

+0

您可以发布重现问题的测试用例吗?你说你正在使用触发器,但在你的例子中没有任何东西显示正在使用的触发器。检查约束失败,但我们不知道如何定义约束。 –

+0

@JustinCave我刚刚修改并包含一个指向[code](http://ideone.com/s2wFLw)的链接。我以为我已经包括它。只是注意到,如果我删除了'if/else'逻辑并使用了'WHEN(:new.isTeamLead ='No')',我得到了2个'no'行。有趣。 – sedeh

回答

2

为什么不只是增加一个独特的基于函数的索引?以下应约束列只有一个每个项目团队负责人:

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

这种利用Oracle的忽略行,其中所有的索引列NULL的。

+0

太棒了!我在修改后的[code](http://ideone.com/s2wFLw)上得到了'SQL Error:ORA-00942:table or view does not exist',但是一切都很好地插入。只是好奇,如果你遇到了同样的错误。谢谢。 – sedeh