触发器未按预期工作

时间:2012-11-26 12:42:34

标签: mysql triggers

我尝试在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 ;

1 个答案:

答案 0 :(得分:1)

我怀疑您的问题是由couponvaluecouponcode变量与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
;