Trigger for column value change?

孤街醉人 提交于 2020-01-23 18:39:31

问题


I am using some SQL triggers to launch actions when a table row gets modified or created. That works like a charm and in my example sets the column gen_date to the current date/time:

CREATE TRIGGER insert_template BEFORE INSERT ON template
FOR EACH ROW BEGIN
  SET new.gen_date := now();
END;

I have another column image and I would like to add a column image_date which should have the value of the current time/date when that field gets updated.

Question: Is it possible to set up a trigger that keeps track of column wise modifications?


回答1:


New values are accessible by NEW., old by OLD.. You can compare them to define if values were changed.

CREATE TRIGGER insert_template BEFORE INSERT ON template
FOR EACH ROW BEGIN
  SET NEW.gen_date := now();
  IF NEW.image <> '' THEN
    SET NEW.image_date := now();
  END IF;
END;

CREATE TRIGGER update_template BEFORE UPDATE ON template
FOR EACH ROW BEGIN
  IF NEW.image <> OLD.image THEN
    SET NEW.image_date := now();
  END IF;
END;


来源:https://stackoverflow.com/questions/35343096/trigger-for-column-value-change

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!