现在我写的触发器有以下问题: 如果我插入的新行与表weeklymeeting中的一个条目冲突,它不应该插入表并给我错误消息。如果NEW行不与表冲突,则新行应插入表中。 但是下面的代码在时间冲突时,它会在不冲突时给我错误,它不能在表中插入新行。 以下触发器的问题在哪里? 如何解决这个问题?
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();
根据BjörnNilsson的评论 我的问题已解决。 正确的解决方案将是:
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 :(得分:1)
无需触发器:
ALTER TABLE weeklymeeting ADD CONSTRAINT section_weekday_unique_constraint UNIQUE (section, weekday);
这会在这两列上创建索引,因此您可能希望颠倒它们的顺序,具体取决于您查询数据的方式