1

I'm trying to add column 'new_id' to a table following the answers on this post.

The objective is to have new_id = 100*id

My SQL version is 5.6.51

This is the query:

ALTER TABLE `mytable`
ADD `new_id` DOUBLE;

CREATE TRIGGER mytrigger BEFORE INSERT ON `mytable`
FOR EACH ROW
BEGIN
    SET NEW.`new_id` = COALESCE(NEW.`id`*100);

This is indeed generating a 'new_id' column, but all values are NULL and the error generated is:

#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
unstuck
  • 563
  • 2
  • 12
  • 29

2 Answers2

1

After some tries this trigger worked for me:

DELIMITER $$
CREATE TRIGGER MyTrigger BEFORE INSERT ON your_table
FOR EACH ROW
BEGIN
    IF NEW.new_id < 0 THEN
        SET NEW.new_id = (select id from your_table order by id desc limit 1) *100;
    ELSEIF NEW.new_id > 0 THEN
        SET NEW.new_id = (select id from your_table order by id desc limit 1) *100;
    ELSEIF NEW.new_id is null THEN
        SET NEW.new_id = (select id from your_table order by id desc limit 1) *100;
    END IF;
END $$
DELIMITER ;

It works in multiple inserted values, too.

Ergest Basha
  • 7,870
  • 4
  • 8
  • 28
1

I believe this works:

ALTER TABLE `my_table`
ADD `xxx` DOUBLE;

  
CREATE TRIGGER mytrigger BEFORE UPDATE ON `my_table`
FOR EACH ROW
SET NEW.`new_id` = COALESCE(NEW.`id`*100);

UPDATE `my_table` SET `xxx` =1;
unstuck
  • 563
  • 2
  • 12
  • 29