我尝试在mysql数据库上执行触发器。 该命令执行成功,但触发器无效。
DELIMITER #
CREATE TRIGGER generate_coupon AFTER INSERT ON order
FOR EACH ROW
BEGIN
DECLARE userid, couponvalue INT;
DECLARE couponcode VARCHAR;
SELECT idUser INTO userid FROM indication WHERE email = NEW.email;
SET couponvalue = 20;
SET couponcode = 'abc123';
INSERT INTO coupon(idUser,idOrder,couponvalue,couponcode) values(userid, NEW.id, couponvalue, couponcode);
END#
DELIMITER ;
答案 0 :(得分:1)
我怀疑您的问题是由couponvalue
和couponcode
变量与coupon
表中具有相同名称的列之间的冲突引起的。正如Local Variable Scope and Resolution所述:
局部变量的名称不应与表列相同。
您可以将触发器简化为以下内容,并在此过程中完全避免此问题:
CREATE TRIGGER generate_coupon AFTER INSERT ON order FOR EACH ROW
INSERT INTO coupon
(idUser, idOrder, couponvalue, couponcode)
SELECT idUser, NEW.id, 20, 'abc123'
FROM indication
WHERE email = NEW.email
;