HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Update one mysql column when another is edited

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
updatecolumnonemysqlanotherwhenedited

Problem

I'm trying to make a datetime field that automatically gets updated with the current time only if there was a change to a certain field.

It seems I have a syntax error.
I try to have last_progress_date that gets the date when the progress_percentage is updated/edited:

CREATE OR ALTER TRIGGER last_progress_date
ON wp_task_mgr
AFTER UPDATE  
AS BEGIN
   IF UPDATE (progress_percentage)
   SET last_progress_date = GETDATE()
END

Solution

The code doesn't look like valid Mysql code:

  • ALTER is not a valid option



  • No AS in Mysql



  • IF UPDATE(column)



  • UPDATE(column) tests whether column updated in SQLServer, not in Mysql



  • IF syntax is invalid (check https://dev.mysql.com/doc/refman/5.5/en/if.html)



  • Finally, you can change value of the record which is being modified in BEFORE trigger, not in AFTER.



You need something like

drop trigger if exists last_progress_date;
delimiter // 
CREATE TRIGGER last_progress_date BEFORE UPDATE ON wp_task_mgr 
FOR EACH ROW     
BEGIN
   --assuming progress_percentage is not nullable; if it is, the condition 
   -- needs to be modified to properly handle NULL values
   IF (NEW.progress_percentage != OLD.progress_percentage) 
   THEN
       SET NEW.last_progress_date = GETDATE();
   END IF;
END;
//
DELIMITER ;

Code Snippets

drop trigger if exists last_progress_date;
delimiter // 
CREATE TRIGGER last_progress_date BEFORE UPDATE ON wp_task_mgr 
FOR EACH ROW     
BEGIN
   --assuming progress_percentage is not nullable; if it is, the condition 
   -- needs to be modified to properly handle NULL values
   IF (NEW.progress_percentage != OLD.progress_percentage) 
   THEN
       SET NEW.last_progress_date = GETDATE();
   END IF;
END;
//
DELIMITER ;

Context

StackExchange Database Administrators Q#120078, answer score: 7

Revisions (0)

No revisions yet.