現在我寫的觸發器有以下問題: 如果我插入的新行與表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();
新行從jsp頁面插入。它與表weeklyMeeting具有相同的列。 – user3382017
衝突時間範圍的任何描述?如果你真的想檢查*重疊*時間範圍,[這個相關的答案](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 ) –