I have create a table as below:
mysql> create table testa (a int, b int, c real);
Query OK, 0 rows affected (0.14 sec)
But when I want to implement a trigger like this, I face some syntax errors:
mysql> create trigger testa_trig
before insert ON testa
FOR EACH ROW
WHEN (NEW.c > 100)
BEGIN
Print "Warning: c > 100!"
END;
ERROR 1064 (42000): 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 'WHEN (NEW.c > 100)
BEGIN
Print "Warning: c > 100!"
END' at line 4
I have checked the documentation at http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html but can't figure out the problem!
My MySQL version:
Server version: 5.5.38-0ubuntu0.12.04.1 (Ubuntu)
Based on the comments below, I tried the following cases, but also crashed:
mysql> create trigger testa_trig before insert on testa for each row
if (NEW.c > 100) begin insert into testb set bc=NEW.c end;
ERROR 1064 (42000): 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 'begin insert into testb set bc=NEW.c end' at line 1
The trigger event that initiates the trigger action can be an INSERT, DELETE, UPDATE, or a SELECT statement. The MERGE statement can also be the triggering event for an UPDATE, DELETE, or INSERT trigger.
The DEFINER clause specifies the MySQL account to be used when checking access privileges at trigger activation time. If the DEFINER clause is present, the user value should be a MySQL account specified as ' user_name '@' host_name ' , CURRENT_USER , or CURRENT_USER() .
An AFTER INSERT Trigger means that MySQL will fire this trigger after the INSERT operation is executed.
Answer: NEW. qty references the qty on the table that the trigger is set on, not the table that is being updated. CREATE TRIGGER after_sales_insert AFTER INSERT ON sales FOR EACH ROW BEGIN UPDATE products SET qty = qty - NEW.
Couple of things wrong here.
Here is code that should work!
DELIMITER $$
CREATE TRIGGER testa_trig
BEFORE INSERT ON testa
FOR EACH ROW BEGIN
IF (NEW.c > 100) THEN
SIGNAL SQLSTATE '02000' SET MESSAGE_TEXT = 'Warning: c > 100!';
END IF;
END$$
DELIMITER ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With