Now the trigger I write has the following problem: if the new row I insert is conflict with one entry in the table weeklymeeting, it should not insert into table and give me error message. While if the NEW row is not conflict with the table, the new row should insert into the table. But the code below when time conflict, it give me error while when not conflict, it cannot insert new row into table. Where is the problem for the below trigger. how to fix this?
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();
Base on the comment from Björn Nilsson my problems fixed. the right solution will be like:
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();