[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 595
  • Last Modified:

MySQL Update Trigger question

I want to track latest Price change for an item.
The table name is res, field names are price, prevprice, priceupdatedate

I need help with writing a trigger that updates the field "prevprice" with the old price when the "price" field is updated and then writes the current time stamp to the priceupdatedate field.

code example appreciated! Thanks!
0
Bang-O-Matic
Asked:
Bang-O-Matic
  • 2
  • 2
1 Solution
 
alpmoonCommented:
Actaully there are useful sample trigger code on the web:

http://dev.mysql.com/doc/refman/5.5/en/trigger-syntax.html
0
 
Chris StanyonCommented:
This is the trigger you need:

DELIMITER $$
CREATE TRIGGER updatePrevPrice BEFORE UPDATE ON res
   FOR EACH ROW BEGIN
      SET NEW.prevprice = OLD.price;
   END;
$$

Open in new window

Make sure your priceupdatedate column is set to a timestamp datatype and is the only one in there, and it'll update automatically as the rows changes.
0
 
Bang-O-MaticAuthor Commented:
@ChrisStanyon
Thanks for the help!

Running the trigger did work for the setting the NEW.prevprice = OLD.price

The priceupdateddate column I changed to timestamp but it did not update the field when updating the price.

I tried:

SET NEW.prevprice = OLD.price, priceupdatedate = NOW();

but that didn't work either says my version of MySQL doesnt support multiple triggers with same action time and event for one table.
0
 
Chris StanyonCommented:
if you edit the trigger using the code I provided it will try and create the same trigger again so you need to delete it first. the timestamp column should update automatically but only if it's the only timestamp column in your table. that may depend on your version of mysql
0
 
Bang-O-MaticAuthor Commented:
Works perfect!
Thanks so much!
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now