简体   繁体   English

MySQL&插入前触发

[英]MySQL & trigger before insert

I need to create a trigger in my database. 我需要在数据库中创建一个触发器。 The trigger must be able to analyse event before insert. 触发器必须能够在插入之前分析事件。 In case of the last event already existing in the database has the same status, the trigger has to cancel the insert and update the last event. 如果数据库中已经存在的最后一个事件具有相同的状态,则触发器必须取消插入并更新最后一个事件。

I tried to create one but I can't add it in my database because of mysql errors: 我尝试创建一个,但是由于mysql错误而无法将其添加到数据库中:

#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 5 

Here the trigger: 这里触发:

CREATE TRIGGER events_before_insert
BEFORE INSERT ON monitoringV2.events
FOR EACH ROW
BEGIN
DECLARE id_last_event;
DECLARE status_last_event;

SELECT id INTO id_last_event, status INTO status_last_event FROM events WHERE module_id=NEW.module_id ORDER BY serverDate DESC LIMIT 1;

IF NEW.status = status_last_event THEN
UPDATE events SET serverDate=NOW() WHERE id=id_last_event;
signal sqlstate '00000' set message_text = "Update instead of insert";
END IF;
END;

Here are information server: 这是信息服务器:

PHP 5.4.6 VC9
Apache 2.4.2 VC9
MySQL 5.5.27
PhpMyAdmin 3.5.2.2

Thanks for your help 谢谢你的帮助

Regards, 问候,

Dorine M. 多琳·M。

You have to change DELIMITER before creating a trigger like this 您必须先更改DELIMITER,然后再创建这样的触发器

DELIMITER $$
CREATE TRIGGER... 
...
END;
$$
DELIMITER ;

You might not need to implement a trigger for this. 您可能不需要为此实现触发器。 The operation you are describing is formally known as UPSERT, ie update or insert. 您所描述的操作被正式称为UPSERT,即更新或插入。

This is how it's done in MySQL and you could also look at REPLACE . 是在MySQL中完成的过程,您还可以查看REPLACE

Here is another question covering this. 是另一个涉及此的问题。

You will need to delimit your create statement: 您需要定界您的create语句:

delimiter //
CREATE...
...
END;
//
DELIMITER ;

and you will probably need to define a type for each variable declared, eg 并且您可能需要为每个声明的变量定义一个类型,例如

DECLARE x INT;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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