MySQL声明导致错误

时间:2013-10-16 09:17:22

标签: mysql triggers declare

我正在尝试创建一个触发器,在将项目插入数据库时​​将其标记为已删除。

可悲的是,我无法让我的DECLARE停止错误,我查看了DECLARE文档以及一些例子,但我必须遗漏一些内容。

我到目前为止的查询是:

CREATE TRIGGER set_deleted BEFORE INSERT ON customercontact
FOR EACH ROW
BEGIN
DECLARE numrow INT; /* line 4 */

        SELECT COUNT(*)
        INTO numrow
        FROM orders
        WHERE NEW.order_id = 1;

        if numrow >= 1 THEN
            SET new.deleted = 1;
        END IF;
END

显示错误消息:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 4 

感谢您的帮助并阻止我defenestrating自己!

1 个答案:

答案 0 :(得分:2)

试试这个:

DELIMITER $$

CREATE TRIGGER set_deleted BEFORE INSERT ON customercontact
FOR EACH ROW
BEGIN
DECLARE numrow INT; /* line 4 */

        SELECT COUNT(*)
        INTO numrow
        FROM orders
        WHERE NEW.order_id = 1;

        if numrow >= 1 THEN
            SET new.deleted = 1;
        END IF;
END$$

DELIMITER ;

创建TRIGGER或STORED PROCEDURE时需要更改分隔符。

默认情况下,MySQL本身将分号识别为语句分隔符,因此必须临时重新定义分隔符以使MySQL将整个存储的程序定义传递给服务器。否则,MySQL会在它到达END语句之前断开CREATE TRIGGER(在第一个分号上,在你的情况下是DECLARE语句)。

您可以查看文档了解更多详情: http://dev.mysql.com/doc/refman/5.5/en/stored-programs-defining.html