I am trying to use trigger
(as suggested here by Bohemian) to constrain how many yes/no
will occur in my table. I want at most one yes
in the isTeamLead
column per unique item in the project
column but can have as many no
as necessary. For no
, it seems the best I can do is use a workaround where I can have something like no1
, no2
, no3
, etc. My code successfully inserts the yes
rows but throws errors on the no
rows.
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;
Here's a snapshot of the error report:
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
Please let me know if any thoughts. Thanks.
Running Oracle Database 11g Enterprise Edition Release 11.2.0.1.0