The default initial value of one column in my database is the same as the row's auto-incremented id. I'm trying to use triggers to set it.
CREATE TRIGGER `default_order_value`
AFTER INSERT ON `clusters`
FOR EACH ROW
BEGIN
UPDATE `clusters` SET `order` = NEW.id WHERE `id` = NEW.id;
END
But this keeps throwing a syntax error
#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
I've tried all sorts of permutations of this with no luck. Can anyone see what I'm doing wrong?
You can create just BEFORE INSERT TRIGGER, it's works like this:
same as below we are using
This worked for me:
As zerkms said, you need to change the delimeter. But since you only use 1 line of code, you don't need the BEGIN and END. And that way, you don't need to change the delimiter either
Since you are getting an error you cannot update the row, I suggest the following:
Do NOT perform the update query at all. On default the order value = the ID value. So when the order value changes, you can update it properly.
If you are requesting the data with php, do something like this:
After you need it updating, you've got the correct value.
I don't think you can do that. An
AFTER INSERT
trigger cannot modify the same table, neither by issuing anUPDATE
nor by something like this:which results in this error:
You can't either use a
BEFORE INSERT
trigger because then theNEW.id
is not known (if you modify the above, theorder
column will get0
value after the Insert.What you can do, is use a transaction:
You get the error because mysql treats
;
in line 5 as the end of your trigger declaration, which obviously leads to the syntax error.So you need to redefine delimiter before you specify the trigger body: