I’m trying to create a trigger where the price entered in the Price column of Courses table would automatically be reduced by 10% after entry. I’m brand new to triggers and am creating my first one; I’m not sure if MySQL lets you declare empty variables which is what I’m assuming I’ll need to subtract it by the original value entered
Delimiter #
CREATE TRIGGER course_discount_table
BEFORE UPDATE ON Courses
FOR EACH ROW
SET New.Price = (New 0.10 * Price)
SET Price = (Price - Price)
END #
DELIMITER ;
Of course, the code is a total mess but would really appreciate any help
2
Answers
the following would every time you update a course take effect and the proce reduced.
Better would be to have a column, that control that behaviour, or a lowest price that would not be underwhelmed.
Several tips:
If you have an
END
, you must also have aBEGIN
.If your trigger body were only one statement, you don’t need a
BEGIN...END
block, and in that case you wouldn’t need to change theDELIMITER
.Every time you reference a column of the new row, prefix it with
NEW.
.Each statement in a block must end with a semicolon.
I have no idea what
SET PRICE = (Price - Price)
is even supposed to do! 🙂Changing the price in a BEFORE UPDATE trigger means it will continue to reduce by 10% after every UPDATE. So if you change the title or the time or whatever, it’ll keep reducing until it’s zero.
It would be better, in my opinion, to record the original price, then
add a generated column to show the discounted price. This you can do without a trigger.
Demo: