2014-03-14 98 views
2

現在我寫的觸發器有以下問題: 如果我插入的新行與表weeklyMeeting中的一個條目發生衝突,它不應該插入到表中並給我提供錯誤消息。如果NEW行不與表衝突,則新行應插入到表中。 但是下面的代碼在時間衝突的時候,它給我錯誤,而不是衝突時,它不能在表中插入新的行。 以下觸發器的問題在哪裏。 如何解決這個問題?postgresql插入觸發器

DROP FUNCTION IF EXISTS time_conflict() CASCADE; 
create or replace function time_conflict() 
returns trigger as 
$BODY$ 
begin 
    if exists( 
     select * 
     from weeklymeeting d 

     where NEW.section_id=d.section_id 
     AND NEW.weekday= d.weekday 
     AND ((d.starttime <= NEW.starttime AND d.endtime > NEW.starttime) OR (d.starttime < NEW.endtime AND d.endtime >= NEW.endtime) OR (d.starttime >=NEW.starttime AND d.endtime <=NEW.endtime)) 
     )THEN 
      RAISE EXCEPTION 'SAME section time conflict!'; 
     else 
     INSERT INTO weeklymeeting VALUES (NEW.*); 
     end if; 
     RETURN NEW; 

end; 
$BODY$ 
    LANGUAGE plpgsql; 

CREATE TRIGGER time_conflict 
BEFORE INSERT ON weeklymeeting for each ROW 
EXECUTE PROCEDURE time_conflict(); 

此基礎上從比約恩尼爾森 固定我的問題發表評論。 合適的解決方案將是這樣的:

DROP FUNCTION IF EXISTS time_conflict() CASCADE; 
create or replace function time_conflict() 
returns trigger as 
$BODY$ 
begin 
    if exists( 
     select * 
     from weeklymeeting d 

     where NEW.section_id=d.section_id 
     AND NEW.weekday= d.weekday 
     AND ((d.starttime <= NEW.starttime AND d.endtime > NEW.starttime) OR (d.starttime < NEW.endtime AND d.endtime >= NEW.endtime) OR (d.starttime >=NEW.starttime AND d.endtime <=NEW.endtime)) 
     )THEN 
      RAISE EXCEPTION 'SAME section time conflict!'; 

     end if; 
     RETURN NEW; 

end; 
$BODY$ 
    LANGUAGE plpgsql; 

CREATE TRIGGER time_conflict 
BEFORE INSERT ON weeklymeeting for each ROW 
EXECUTE PROCEDURE time_conflict(); 
+0

新行從jsp頁面插入。它與表weeklyMeeting具有相同的列。 – user3382017

+0

衝突時間範圍的任何描述?如果你真的想檢查*重疊*時間範圍,[這個相關的答案](http://stackoverflow.com/questions/4480715/find-overlapping-date-ranges-in-postgresql/15305292#15305292)可能是幫幫我。對於互斥的每週時間範圍,[看這裏。](http://stackoverflow.com/questions/22108477/native-way-of-performing-this-hours-of-operation-query-in-postgresql/22111524#22111524 ) –

回答

1

無需觸發:

ALTER TABLE weeklymeeting ADD CONSTRAINT section_weekday_unique_constraint UNIQUE (section, weekday); 

這將創建在這兩個列的索引,所以你可能要扭轉他們的秩序,這取決於如何您查詢數據

+0

我需要使用觸發器,因爲它需要教授 – user3382017

+0

好吧,你應該返回NEW,否則它不會工作,因爲它是一個觸發前。然後你不需要手動進行插入。 –

+0

我已經改變爲返回新的,但它仍然給我錯誤 – user3382017