带有变量Input的MySQL触发器

时间:2012-07-31 19:47:05

标签: mysql

我正在尝试为UDATES创建表的触发器。我以为我可以使用多个触发器执行此操作,但我猜MySQL在同一类型的一个表上不支持多个触发器。所以我被迫将其包含在一个触发器中。

基本上我试图根据当前表中更新的内容将新记录插入到不同的表中。

这是我到目前为止所做的工作:

BEGIN
-- Definition start
INSERT INTO prices (stationID, price, type, 
prevPrice, prevDate, dateCreated, apiKey, uid) 
VALUES(NEW.stationID, NEW.regPrice, 'reg', OLD.regPrice,
OLD.regDate, NEW.regDate, NEW.lastApiUsed, NEW.lastUpdatedBy);
-- Definition end
END

我需要做的是type可能会根据用户提供的类型而改变。由于用户可能只在给定时间更新一种类型。我在考虑IF IF THEN声明,但我不确定如何让它发挥作用。我以为我可以在IF语句中使用列名的String值,但我不确定是否可以。

这样的事情:

    BEGIN
    -- Definition start
    IF(type == 'reg') THEN
    INSERT INTO prices (stationID, price, type, 
    prevPrice, prevDate, dateCreated, apiKey, uid) 
    VALUES(NEW.stationID, NEW.regPrice, 'reg', OLD.regPrice,
    OLD.regDate, NEW.regDate, NEW.lastApiUsed, NEW.lastUpdatedBy);
    END IF;
    -- Definition end
    END

1 个答案:

答案 0 :(得分:0)

我能够使用IF THEN ELSE来完成交易。然后我测试了NULL值的条件。如果是TRUE,那么我就运行了我的代码。现在由于某种原因它只执行一个INSERT命令,即使UPDATE不止一个。有什么想法吗?

BEGIN
-- Definition start
IF(NEW.regPrice IS NOT NULL) THEN
INSERT INTO prices (stationID, price, type, 
prevPrice, prevDate, dateCreated, apiKey, uid) 
VALUES(NEW.stationID, NEW.regPrice, 'reg', OLD.regPrice,
OLD.regDate, NEW.regDate, NEW.lastApiUsed, NEW.lastUpdatedBy);

ELSEIF(NEW.midPrice IS NOT NULL) THEN
INSERT INTO prices (stationID, price, type, 
prevPrice, prevDate, dateCreated, apiKey, uid) 
VALUES(NEW.stationID, NEW.midPrice, 'mid', OLD.midPrice,
OLD.midDate, NEW.midDate, NEW.lastApiUsed, NEW.lastUpdatedBy);

ELSEIF(NEW.prePrice IS NOT NULL) THEN
INSERT INTO prices (stationID, price, type, 
prevPrice, prevDate, dateCreated, apiKey, uid) 
VALUES(NEW.stationID, NEW.prePrice, 'pre', OLD.prePrice,
OLD.preDate, NEW.preDate, NEW.lastApiUsed, NEW.lastUpdatedBy);
END IF;
-- Definition end
END