如何在触发器中访问INSERTED
表的值?
例如:
INSERT INTO sales (sku, qty)
VALUES
(1001, 5), //I need these values in the trigger
(1002, 1)
...
这是我的触发器:
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;
请注意,sales.sku
是products
表的外键。
SQL Server具有INSERTED
关键字,该关键字似乎不适用于MySQL。
NEW.qty
引用设置触发器的表上的qty
,不是要更新的表。
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;
答案 0 :(得分:3)
给出:
INSERT INTO sales (sku, qty)
VALUES
(1001, 5), //I need these values in the trigger
(1002, 1)
...
我相信你想要这个:
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;
参考文献: