MySQL Trigger: Prevent Insert by IF statement

2019-09-10 18:49发布

I try to write my first trigger for a MySQL Database. It should prevent an insert (and later also updates) on "course_student" in context of the current time and the given timestamps in "capacity", but i'm still getting a syntax error.

DELIMITER $$

CREATE TRIGGER checkSubscribeTimeCourse 
BEFORE INSERT ON course_student
REFERENCING NEW AS new
FOR EACH ROW 

BEGIN

    IF (SELECT COUNT(*) FROM capacity c, course_capacity cc 
        WHERE c.cid = cc.cid 
        AND cc.cid = new.cid
        AND (c.end >= CURRENT_TIMESTAMP OR c.end IS NULL)
        AND (c.start <= CURRENT_TIMESTAMP OR c.start IS NULL)<1)
    THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'Error'
    END IF

END

DELIMITER ;

I translated all names; so maybe there are typing errors.

1条回答
Deceive 欺骗
2楼-- · 2019-09-10 19:23

You have a few missing commas and some made up sql and a missing delimter at the end.

DELIMITER $$

CREATE TRIGGER checkSubscribeTimeCourse 
BEFORE INSERT ON course_student
FOR EACH ROW
BEGIN

    IF (SELECT COUNT(*) FROM capacity c, course_capacity cc 
        WHERE c.cid = cc.cid 
        AND cc.cid = new.cid
        AND (c.end >= CURRENT_TIMESTAMP OR c.end IS NULL)
        AND (c.start <= CURRENT_TIMESTAMP OR c.start IS NULL)<1)
    THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'Error';
    END IF;

END$$

DELIMITER ;
查看更多
登录 后发表回答