这是我的代码,该如何修改CREATE TRIGGER tr_lineitem_quantity_update AFTER UPDATE ON lineitem FOR EACH ROW BEGIN DECLARE p_retailprice DOUBLE; SELECT retailprice INTO p_retailprice FROM part WHERE partkey = NEW.partkey; IF (NEW.quantity != OLD.quantity) THEN UPDATE lineitem AS l SET l.extendedprice = p_retailprice * NEW.quantity * NEW.discount WHERE l.orderkey = NEW.orderkey AND l.linenumber = NEW.linenumber; UPDATE partsupp AS p SET p.availqty = p.availqty - (NEW.quantity - OLD.quantity) WHERE p.partkey = NEW.partkey AND p.suppkey = NEW.suppkey; END IF; END;
时间: 2023-06-27 07:02:54 浏览: 149
QTreeWidgetItem的setData(int column,int role,QVariant& data)等,
这段代码是一个在lineitem表中添加触发器的SQL语句,目的是在lineitem表中的数据被更新时,自动更新extendedprice和partsupp表中的availqty字段。
修改建议:
1. 建议添加错误处理机制,例如使用SIGNAL语句抛出异常;
2. 建议添加事务处理机制,例如使用START TRANSACTION和COMMIT语句;
3. 建议对代码进行优化,例如使用JOIN语句代替多个UPDATE语句。
下面是修改后的代码:
DELIMITER //
CREATE TRIGGER tr_lineitem_quantity_update
AFTER UPDATE ON lineitem
FOR EACH ROW
BEGIN
DECLARE p_retailprice DOUBLE;
DECLARE old_quantity INT;
DECLARE new_quantity INT;
SELECT retailprice INTO p_retailprice FROM part WHERE partkey = NEW.partkey;
IF (NEW.quantity != OLD.quantity) THEN
START TRANSACTION;
SET old_quantity = OLD.quantity;
SET new_quantity = NEW.quantity;
UPDATE lineitem AS l
INNER JOIN partsupp AS p ON l.partkey = p.partkey AND l.suppkey = p.suppkey
SET l.extendedprice = p_retailprice * new_quantity * NEW.discount,
p.availqty = p.availqty - (new_quantity - old_quantity)
WHERE l.orderkey = NEW.orderkey AND l.linenumber = NEW.linenumber;
IF (ROW_COUNT() = 0) THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Update failed';
END IF;
COMMIT;
END IF;
END //
DELIMITER ;
阅读全文