I am new to triggers but want to know how I can use one in my database.
I have created a table for a maintenance log, a parts inventory, and a parts_used junction table. When maintenance is carried out the parts and log id's a inserted into parts_used. I want to be able to take subtract 1 from the quantity in the inventory for that part.
Maintenance log
CREATE TABLE maintenance_log (
idlog int (4) AUTO_INCREMENT,
idVehicle int (2),
description VARCHAR (80),
entry_date DATE(),
release_date DATE,
idMechanic int (2),
FOREIGN KEY (idVehicle) REFERENCES vehicles(idVehicle),
FOREIGN KEY (idMechanic) REFERENCES mechanics(idMechanic),
PRIMARY KEY (idlog)
);
Parts
CREATE TABLE parts (
idParts int(3) AUTO_INCREMENT,
part_description VARCHAR (60),
quantity int (2),
PRIMARY KEY (idParts)
);
parts_used
CREATE TABLE parts_used(
idParts int (3),
idlog int (4),
CONSTRAINT PK_partUsed PRIMARY KEY
(
idParts,
idlog
),
FOREIGN KEY (idParts) REFERENCES parts(idParts),
FOREIGN KEY (idlog) REFERENCES maintenance_log (idlog)
);
My current trigger just returns ERROR with no other message. This is what I am using.
CREATE TRIGGER subtract_quantity
AFTER INSERT ON parts_used FOR EACH ROW
BEGIN
UPDATE parts
SET parts.quantity = parts.quantity - 1
WHERE parts.idParts = NEW.idParts
END
DELIMITER ;
Can anybody help or offer any advice?
Best Answer
You need to have
DELIMITER
directives both before and after theCREATE TRIGGER
statement, you need to end individual simple statements with semicolons, and you need to end the completeCREATE TRIGGER
with the delimiter specified in the firstDELIMITER
directive:However, in this case your entire trigger body is a single
UPDATE
statement, so you can omit both theBEGIN ... END
statements and theDELIMITER
directives:(The
DELIMITER
directives allow the parser to distinguish between the end of a compound-statement trigger or procedure body and the ends of the individual simple statements it contains, and are only required by some MySQL clients.)