Question

I'm enjoying all that MySQL can do. I want to learn how I can have a MySQL Trigger to update the Total Cost of a MySQL column where UNITS * PRICE will (of course) equal total cost.

INVOICE TABLE includes ( Price, Units, Total Cost)

    CREATE TRIGGER TRG_TOTAL_COST 
    AFTER INSERT ON INVOICE
    FOR EACH ROW 
    BEGIN 
    --1) Get the TOTAL
    SELECT TOTAL_COST from INVOICE
    --2) Compute total
    TOTAL_COST= UNITS * 
    PRICE; 
    END;
Was it helpful?

Solution

While I'm not sure this is very good database design, you could accomplish this very easily by

CREATE TRIGGER TRG_TOTAL_COST BEFORE INSERT ON INVOICE FOR EACH ROW
SET NEW.TOTAL_COST = NEW.UNITS * NEW.PRICE

but I do not understand why you would want to do this in a trigger? You have all the data you need at insertion time, so you could just do the product right in the insert.

Or unless you have a good reason for actually wanting to store it, why not just leave out the potentially redundant column and calculate the product in your selects?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top