写入触发器语句出错

时间:2015-09-08 10:27:01

标签: mysql triggers

我想将表的大小限制为X行(例如,我会使用5行)。达到限制时,我想将最旧的行复制到另一个表,然后将其删除。我目前有:

CREATE TRIGGER LimitRows BEFORE INSERT ON MyTable
FOR EACH ROW BEGIN
    IF (SELECT COUNT(*) FROM MyTable) >= 5 THEN

    INSERT INTO HistoryTable
    SELECT *
    FROM MyTable A
    WHERE vhID = A.min(vhID);

    DELETE FROM MyTable
    WHERE vhID = min(vhID); 

    END IF;    
END;

目前,我收到错误:

  

您的SQL语法有错误;查看与您的MySQL服务器版本相对应的手册,以获得在''附近使用的正确语法。在第8行

如何正确编写此触发器?另外,如果从100行开始,我如何修改将表格缩减为5行?

1 个答案:

答案 0 :(得分:1)

您需要先更改分隔符

delimiter |
CREATE TRIGGER LimitRows BEFORE INSERT ON MyTable
FOR EACH ROW BEGIN
    IF (SELECT COUNT(*) FROM MyTable) >= 5 THEN

    INSERT INTO HistoryTable
    SELECT *
    FROM MyTable A
    WHERE vhID = A.min(vhID);

    DELETE FROM MyTable
    WHERE vhID = min(vhID); 

    END IF;    
END
|
delimiter ;

否则触发器定义将在第一个;处结束,这将使其不完整。