简体   繁体   中英

MySQL Trigger updates all rows even if a distinct where clause is given

Refer to the following trigger,

create trigger trigger_update_rows after insert on transaction for each row

DECLARE tr_type VARCHAR(15);
DECLARE tr_op VARCHAR(10);
DECLARE tr_amt FLOAT(8,2);
DECLARE tr_qnt INTEGER;
DECLARE item_id INTEGER;
SET tr_type = NEW.TRANSACTION_TYPE;
SET tr_op = (SELECT TRANSACTION_TYPE_OPERATION FROM transaction_type WHERE 
TRANSACTION_TYPE_NAME=tr_type limit 1);
SET tr_amt = NEW.TRANSACTION_AMOUNT;
SET tr_qnt = NEW.QUANTITY;
SET item_id = NEW.ITEM_ID;
IF tr_op = 'ADD' THEN
update item set QUANTITY_AVAILABLE=QUANTITY_AVAILABLE-
tr_qnt,QUANTITY_SOLD=QUANTITY_SOLD+tr_qnt,AVAILABLE_GOODS_VALUE = 
AVAILABLE_GOODS_VALUE - tr_amt,SOLD_GOODS_VALUE=SOLD_GOODS_VALUE+tr_amt 
where ITEM_ID=item_id;
ELSEIF tr_op = 'SUBTRACT' THEN
update item set QUANTITY_AVAILABLE=QUANTITY_AVAILABLE+tr_qnt,QUANTITY_BOUGHT=QUANTITY_BOUGHT+tr_qnt,AVAILABLE_GOODS_VALUE=AVAILABLE_GOODS_VALUE+tr_amt,BOUGHT_GOODS_VALUE=BOUGHT_GOODS_VALUE+tr_amt where ITEM_ID=item_id;
END IF;
END 

ITEM_ID is a primary key in the table item and the following is the transaction row inserted

insert into transaction(TRANSACTION_DATE,TRANSACTION_TYPE,ITEM_ID,QUANTITY,TRANSACTION_AMOUNT,ACCOUNT_ID,BUYER,SELLER) values ('2017-08-12','BUY',2,5,500.00,3,1,2);

What is making the above trigger update all rows in item instead following the where clause

You problem is:

where ITEM_ID = item_id;

You may think that one of the item_id s is somehow connected to the variable. It is not.

Rename the variable to something like v_item_id and then use:

where item_id = v_item_id

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