[英]Mysql trigger is not updating record
我有兩個表“產品”和“股票”。 產品表將包含所有產品。 在庫存表中,我每次都將產品的庫存保存為新條目。
我有兩種產品。 “1”類型的產品將有庫存作為數字,“0”類型的產品將有庫存作為重量。 因此,在產品表中,我創建了兩列“stock_weight(保持在庫存表中輸入的總重量)”和“件(保持在庫存表中輸入的總數量)”。
為此,我在庫存表上創建了一個觸發器,每當我將新記錄插入此表時,它將執行以更新產品表中的總重量或數量(件)。 下面是觸發器的代碼:
BEGIN
DECLARE product_type tinyint default 0;
SET product_type = (Select product_type from products where id = NEW.product_id);
IF (product_type = 0) THEN
UPDATE products set stock_weight = stock_weight + NEW.net_weight where id = NEW.product_id;
ELSE
UPDATE products set stock_pieces = stock_pieces + NEW.pieces where id = NEW.product_id;
END IF;
END
但是在任何產品的庫存表中插入新記錄后,產品表中沒有任何更新。 我已經調試了觸發器並且觸發器正在執行,但產品表中沒有任何更新。
有人可以告訴我我錯過了什么以及我做錯了什么嗎?
不要為變量賦予與列相同的名稱並預期為空
DROP TABLE IF EXISTS PRODUCTS,STOCKS;
create table products(id int,product_type int,stock_weight int,stock_pieces int);
create table stocks(product_id int,net_weight int,pieces int);
drop trigger if exists t;
delimiter $$
create trigger t after insert on stocks
for each row
BEGIN
DECLARE vproduct_type tinyint default 0;
SET vproduct_type = (Select product_type from products where id = NEW.product_id);
IF (vproduct_type = 0) THEN
UPDATE products set stock_weight = coalesce(stock_weight,0) + NEW.net_weight where id = NEW.product_id;
ELSE
UPDATE products set stock_pieces = coalesce(stock_pieces,0) + NEW.pieces where id = NEW.product_id;
END IF;
END $$
delimiter ;
insert into products values(1,1,null,null),(2,0,null,null);
insert into stocks values(1,null,10),(2,10,null);
select * from products;
+------+--------------+--------------+--------------+
| id | product_type | stock_weight | stock_pieces |
+------+--------------+--------------+--------------+
| 1 | 1 | NULL | 10 |
| 2 | 0 | 10 | NULL |
+------+--------------+--------------+--------------+
2 rows in set (0.001 sec)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.