问题
I am going create a trigger in xampp.
CREATE TRIGGER testref BEFORE INSERT ON test1
FOR EACH ROW
BEGIN
INSERT INTO test2 SET a2 = NEW.a1;
DELETE FROM test3 WHERE a3 = NEW.a1;
UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
END;
but I have got errors:
CREATE TRIGGER testref BEFORE INSERT ON test1
FOR EACH
ROW
BEGIN
INSERT INTO test2
SET a2 = NEW.a1;
MySQL said: Documentation
#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
Before, i create 4 table:
CREATE TABLE test1(a1 INT);
CREATE TABLE test2(a2 INT);
CREATE TABLE test3(a3 INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
CREATE TABLE test4(
a4 INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
b4 INT DEFAULT 0
);
Please help me. Thank you alot!
回答1:
Change the delimiter first, otherwise the semicolons in your procedure break the syntax. See the example half way down this page on creating procedures in the MySQL docs (copied below to save you time).
mysql> delimiter //
mysql> CREATE PROCEDURE simpleproc (OUT param1 INT)
-> BEGIN
-> SELECT COUNT(*) INTO param1 FROM t;
-> END//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> CALL simpleproc(@a);
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @a;
+------+
| @a |
+------+
| 3 |
+------+
1 row in set (0.00 sec)
Update: Perhaps the following...
DELIMITER //
CREATE TRIGGER testref BEFORE INSERT ON test1
FOR EACH ROW
BEGIN
INSERT INTO test2 SET a2 = NEW.a1;
DELETE FROM test3 WHERE a3 = NEW.a1;
UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
END//
DELIMITER ;
回答2:
Have a look if there is a DILIMITER field in your phpmyadmin version, just below the SQL editor. Set your delimiter there, for example - '$$', and write this SQL code -
CREATE TRIGGER testref BEFORE INSERT ON test1
FOR EACH ROW
BEGIN
INSERT INTO test2 SET a2 = NEW.a1;
DELETE FROM test3 WHERE a3 = NEW.a1;
UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
END$$
If your phpmyadmin do not have this option (it can be on old versions), and if it is possible to connect to server using another tool, then try to use another MySQL client, e.g. - dbForge Studio for MySQL (free express edition).
回答3:
Use following for creating trigger
delimiter |
CREATE TRIGGER testref BEFORE INSERT ON test1
FOR EACH ROW
BEGIN
INSERT INTO test2 SET a2 = NEW.a1;
DELETE FROM test3 WHERE a3 = NEW.a1;
UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
END;
|
That is... you must use delimiter..
Delimiter is used to define the end of the query. By default it is semicolumn(;). Here we used DELIMITER command to change the default delimiter so that we can use ';' insdie trigger definition
来源:https://stackoverflow.com/questions/13132420/error-when-creating-a-trigger-in-mysql-5-5-27