How can I access the the INSERTED table's values in a trigger?
For example:
INSERT INTO sales (sku, qty)
VALUES
(1001, 5), //I need these values in the trigger
(1002, 1)
...
This is my trigger:
DELIMITER $$
CREATE TRIGGER after_sales_insert
AFTER INSERT ON sales
FOR EACH ROW BEGIN
UPDATE products
SET NEW.qty = OLD.qty - INSERTED.qty
WHERE sku = INSERTED.sku;
END;
$$
DELIMITER;
Note that sales.sku is a foreign key for the products table.
SQL Server has the INSERTED keyword, which doesn't seem to work for MySQL.
Answer:
NEW.qty references the qty on the table that the trigger is set on, not the table that is being updated.
CREATE TRIGGER after_sales_insert
AFTER INSERT ON sales
FOR EACH ROW BEGIN
UPDATE products
SET qty = qty - NEW.qty
WHERE sku = NEW.sku;
END;