以上代码为什么会出现这样的报错1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE sale_count INT; SELECT COUNT(*) INTO sale_count FROM Sale WHERE Ord' at line 7
时间: 2023-07-07 09:43:06 浏览: 122
这个报错是因为MySQL中不支持在触发器中使用DECLARE语句,你需要将其移动到BEGIN语句之前。可以参考以下修改后的代码:
```
CREATE TRIGGER after_order_complete1
AFTER UPDATE ON Order_dd
FOR EACH ROW
BEGIN
DECLARE sale_count INT;
IF NEW.Order_status = '已完成' THEN
-- 判断销售表中是否已经存在相同的销售记录
SELECT COUNT(*) INTO sale_count FROM Sale WHERE Order_id = NEW.Order_id AND Product_id = NEW.Product_id;
IF sale_count = 0 THEN
-- 插入一条新的销售记录
INSERT INTO Sale (Product_id, Order_id, Order_date, Employee_id, Customer_id, Sale_num, Sale_amount)
VALUES (NEW.Product_id, NEW.Order_id, NEW.Order_date, FLOOR(RAND() * (4 - 1 + 1)) + 1, NEW.Customer_id, NEW.Product_num, NEW.Order_price);
END IF;
-- 更新销售表中对应的订单的产品ID
UPDATE Sale SET Product_id = NEW.Product_id WHERE Order_id = NEW.Order_id;
END IF;
END;
```
在修改后的代码中,我将DECLARE语句移到了BEGIN语句之前,以解决报错问题。
阅读全文