简体   繁体   中英

postgresql trigger for insert

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();

No need for a trigger:

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

This creates an index on those two columns, so you might want to reverse the order of them, depending how you query the data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM