简体   繁体   中英

mysql trigger to add or subtract from in-stock quantity, subtract 1 when item hired & add 1 on when item return

Hi Im having a problem with my mysql trigger syntax, I want it to update my copy_instock row on NEW transaction_id, when movie is hired to subtract 1 from copy_instock, then update when movie is returned to add 1 back on to copy_instock. OR how can I achieve this in a different way from MySql. My table is below and my trigger that is not correct

CREATE TABLE IF NOT EXISTS `hires` (
`transaction_id` int(11) NOT NULL,
`movie_id` int(11) NOT NULL,
`customer_id` int(11) NOT NULL,
`hire_cost` double(4,2) NOT NULL DEFAULT '3.00',
`date_hired` date DEFAULT NULL,
`days_hire` int(11) NOT NULL DEFAULT '1',
`date_returned` date DEFAULT NULL,
`total_cost` double(4,2) DEFAULT NULL,
`copy_instock` int(3) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;



CREATE TRIGGER update_instock AFTER INSERT ON hires
FOR EACH ROW
BEGIN
if (date_returned != NULL) {
UPDATE hires SET (NEW.copy_instock = OLD.copy_instock - 1)
}
Elseif (date_returned != date) {
UPDATE hires SET (NEW.copy_instock = OLD.copy_instock + 1)
END

You need to set de delimiter

DELIMITER $$

CREATE TRIGGER update_instock AFTER INSERT ON hires
FOR EACH ROW
BEGIN
-- your code
END$$

DELIMITER ;

There should be no { and } in the code. Correct syntax is:

IF ... THEN
    ...
ELSEIF ... THEN
    ...
END IF;

Also something != null will retrun wrong values, it should be:

something IS NLLL

or

something IS NOT NULL

Reference

I don't know, if this is what you tried to achieve, however it has corrected syntax:

CREATE TRIGGER update_instock AFTER INSERT ON hires
FOR EACH ROW
BEGIN
    IF (date_returned IS NULL) THEN
        UPDATE hires SET NEW.copy_instock = OLD.copy_instock - 1;
    ELSEIF (date_returned IS NOT NULL) THEN
        UPDATE hires SET NEW.copy_instock = OLD.copy_instock + 1;
    END IF;
END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM