如何修复此MySQL触发器语句?

时间:2017-04-04 03:59:20

标签: mysql database triggers

无法找到问题,现在已经尝试了一段时间

CREATE
    TRIGGER `checkin_enforcement` BEFORE INSERT
    ON `booking` 
    FOR EACH ROW BEGIN

        IF (NEW.checkinDate < NEW.checkoutDate) THEN
            INSERT INTO booking (bookingID, hotelNo, guestNo, checkinDate, checkoutDate, roomNo) VALUES (NEW.bookingID, NEW.hotelNo, NEW.guestNo, NEW.checkinDate, NEW.checkoutDate, NEW.roomNo);

        ELSE
            signal sqlstate '45000' set message_text = 'The checkin date must be less than the checkout date!';
        END IF;


    END$$

#1064 - 您的SQL语法出错;查看与您的MySQL服务器版本相对应的手册,以获得在&#39;&#39;附近使用的正确语法。第7行

2 个答案:

答案 0 :(得分:0)

如果条件通过,您不需要插入行。你只需要在没有错误时抛出错误。

此外,我将on insert更改为on insert or update,因为您可能希望即使在表中插入数据后仍然强制执行此规则。如果没有,只需将其更改为on insert

试试这个:

delimiter $$

create trigger checkin_enforcement 
before insert or update on booking
for each row 
begin
    if (new.checkindate >= new.checkoutdate) then
        signal sqlstate '45000' set message_text = 'the checkin date must be less than the checkout date!';
    end if;
end$$

答案 1 :(得分:0)

CREATE TRIGGER `checkin_enforcement` 
BEFORE INSERT ON `booking` 
FOR EACH ROW
IF NEW.checkinDate >= NEW.checkoutDate THEN 
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'The check-in date must be before the check-out date!'; 
END IF

FOR FOR EACH ROW后不需要BEGIN