Search code examples
mysqlmysql-error-1064mysql-connector

'WHERE' condition in an UPDATE TRIGGER giving syntax error :mysql version 5.7


I am using mysql database(VERSION 5.7).

I created a table with the following CREATE command:

CREATE TABLE `attendance` (
  `id` varchar(11) NOT NULL,
  `hash` char(8) NOT NULL,
  `time_in` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `time_out` datetime DEFAULT NULL,
  `time_spent` time DEFAULT NULL,
  `purpose` char(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

I have a trigger with the following query:

DELIMITER $$

CREATE TRIGGER test_trigger 
BEFORE UPDATE ON attendance 
FOR EACH ROW 
BEGIN 
SET NEW.time_spent=TIMEDIFF(NEW.time_out,OLD.time_in) WHERE OLD.time_spent IS NULL; 
END$$

DELIMITER ;

But mysql gives the following error:

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 'WHERE OLD.time_spent IS NULL; END' at line 1

(The where condition makes sure that only current days records get updated)

How am I supposed to write the query?


Solution

  • You can't use a WHERE clause with SET inside a trigger. Use IF instead:

    DELIMITER $$
    
    CREATE TRIGGER test_trigger 
    BEFORE UPDATE ON attendance 
    FOR EACH ROW 
    BEGIN
        IF OLD.time_spent IS NULL THEN
            SET NEW.time_spent = TIMEDIFF(NEW.time_out, OLD.time_in);
        END IF;
    END$$
    
    DELIMITER ;