How do I create this MySQL trigger?
I have a table called customer
whic开发者_开发技巧h has, among others, a column called name
and a column called first_name_start
. I want first_name_start
to be equal to SUBSTRING(name, 1, 4)
. How would I create a trigger that makes sure this happens?
DELIMITER $$
CREATE TRIGGER trigger_name BEFORE INSERT ON your_table
FOR EACH ROW
BEGIN
SET NEW.first_name_start = SUBSTRING(NEW.name, 1, 4);
END$$
CREATE TRIGGER trigger_name BEFORE UPDATE ON your_table
FOR EACH ROW
BEGIN
SET NEW.first_name_start = SUBSTRING(NEW.name, 1, 4);
END$$
DELIMITER ;
Unfortunately, I didn't get time to test this, it might be completely wrong.
Why not just make a view which adds the first_name_start
if you really need it as a column? Then you won't be storing redundant data, but you will be able to use it as if you were.
精彩评论