我正在嘗試使用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
檢查約束允許哪些值?你試圖插入'否' - 如果檢查約束設置爲允許'是'和'否',那麼它將不允許'否'。 –
您可以發佈重現問題的測試用例嗎?你說你正在使用觸發器,但在你的例子中沒有任何東西顯示正在使用的觸發器。檢查約束失敗,但我們不知道如何定義約束。 –
@JustinCave我剛剛修改幷包含一個指向[code](http://ideone.com/s2wFLw)的鏈接。我以爲我已經包括它。只是注意到,如果我刪除了'if/else'邏輯並使用了'WHEN(:new.isTeamLead ='No')',我得到了2個'no'行。有趣。 – sedeh