MYSQL触发器 - 在插入之前从另一个表更新表中的值

时间:2013-07-09 02:05:31

标签: mysql triggers

我想要的是在从另一个表插入之前更新一个值 - 这就是我所拥有的:

2桌

hbrpg_geo{
...
id INT       //id that needs to be written into hbrpg_person
zip VARCHAR(10) //contains postcode
...
}

hbrpg_person{
...
 fk_postcode     // initially it's filled with UK postcode - but trigger should change value to id of hbrpg_geo of matching postcode (hbrpg_geo.zip). 
...
}

触发:

...

BEGIN
    DECLARE NP_VAR integer;
    DECLARE OP_VAR TEXT;
    SET OP_VAR = NEW.fk_postcode;
    SET TE_VAR = OP_VAR;
    SELECT hbrpg_geo.id INTO NP_VAR FROM hbrpg_geo WHERE hbrpg_geo.zip = OP_VAR;
    SET NEW.fk_postcode = NP_VAR;
END

这一切似乎都与以下方面有关:

SET OP_VAR = NEW.fk_postcode;

如果我用引号中的有效英国邮政编码替换NEW.fk_postcode(即:“W1 3XX”),它工作正常,触发器用hbrpg_geo表的id替换字段fk_postcode。

我做错了什么?如何将NEW.fk_postcode的值赋给我刚刚声明的变量?

1 个答案:

答案 0 :(得分:0)

您有分配顺序:

SET OP_VAR = NEW.fk_postcode;
. . .
SET NEW.fk_postcode = NP_VAR;

new.fk_postcode具有相同的类型。但这些列分别是textinteger

您需要修复类型不兼容的问题。我的猜测是fk_postcode实际上是一个整数,并且与值(将是一个字符串)分开。