drop trigger if exists WW; CREATE TRIGGER WW AFTER INSERT ON td_order FOR EACH ROW BEGIN DECLARE p_price DECIMAL(10, 2); DECLARE o_zk INT; DECLARE p_no INT; DECLARE p_stock INT; SELECT Gdiscounts INTO o_zk FROM tb_imformation WHERE Ino = NEW.Ino; SELECT Pprice,Pcount,pno INTO p_price,p_stock ,p_no FROM tb_products WHERE pno = NEW.pno; SELECT Pcount INTO p_stock FROM tb_products WHERE pno = NEW.pno; FOR UPDATE; IF p_stock < Ocount THEN ROLLBACK; ELSE UPDATE tb_product SET Pcount = p_stock - Ocount WHERE pno = p_no; UPDATE order_table SET Omoney = p_price * o_zk WHERE Ino = NEW.Ino; END IF; END; 这段代码的意思是什么,错误是‘’在存储函数或触发器中不允许显式或隐式提交‘’需要如何修改
时间: 2024-02-14 19:05:43 浏览: 133
这段代码是创建一个名为`WW`的触发器,目的是在向`td_order`表中插入新数据后自动触发。该触发器会根据商品单价、订单折扣和库存数量计算出订单金额,并将其写入`order_table`表中的`Omoney`字段中。同时,它还会更新`tb_products`表中对应商品的库存数量,如果库存不足则会撤销之前的操作并抛出异常。
然而,这段代码中存在一个错误,即在触发器中使用了`ROLLBACK`语句,而在存储函数或触发器中是不允许显式或隐式提交的。为了解决这个问题,可以将`ROLLBACK`语句修改为`SIGNAL`语句,抛出一个异常并回滚之前的操作。修改后的代码如下:
```
DROP TRIGGER IF EXISTS WW;
DELIMITER //
CREATE TRIGGER WW AFTER INSERT ON td_order FOR EACH ROW
BEGIN
DECLARE p_price DECIMAL(10, 2);
DECLARE o_zk INT;
DECLARE p_no INT;
DECLARE p_stock INT;
SELECT Gdiscounts INTO o_zk FROM tb_imformation WHERE Ino = NEW.Ino;
SELECT Pprice, Pcount, pno INTO p_price, p_stock, p_no FROM tb_products WHERE pno = NEW.pno FOR UPDATE;
IF p_stock < NEW.Ocount THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '库存不足,无法完成操作';
ELSE
UPDATE tb_products SET Pcount = p_stock - NEW.Ocount WHERE pno = p_no;
UPDATE order_table SET Omoney = p_price * o_zk WHERE Ino = NEW.Ino;
END IF;
END//
DELIMITER ;
```
修改后的代码中,将`ROLLBACK`语句修改为了`SIGNAL`语句,并在触发器中添加了`DELIMITER`语句以支持多条语句的执行。
阅读全文