简体   繁体   English

MYSQL触发器-插入之前更新其他表中的表中的值

[英]MYSQL Trigger - update values in table from other table before insert

What I am trying is to update a value before insert from another table - here is what I've got: 我正在尝试在从另一个表插入之前更新值-这是我所拥有的:

2 Tables 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). 
...
}

Trigger: 触发:

...

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

It all appears to be working apart from: 一切似乎都与以下工作不同:

SET OP_VAR = NEW.fk_postcode;

If I replace NEW.fk_postcode with a valid UK postcode in quotes (ie: "W1 3XX") it works fine and the trigger replaces the field fk_postcode with the id of hbrpg_geo table. 如果将NEW.fk_postcode替换为带引号的有效英国邮政编码(即:“ W1 3XX”),它将正常工作,并且触发器将hkpg_geo表的ID替换为字段fk_postcode。

What I am doing wrong ? 我做错了什么? How can I assign the value of NEW.fk_postcode to the variable I just declared? 如何将NEW.fk_postcode的值分配给刚刚声明的变量?

You have the sequence of assignments: 您具有分配顺序:

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

The column new.fk_postcode has the same type. new.fk_postcode具有相同的类型。 But the columns are, respectively, text and integer . 但是这些列分别是textinteger

You need to fix the type incompatibility. 您需要修复类型不兼容。 My guess is that fk_postcode is actually an integer and separate from the value (which would be a string). 我的猜测是fk_postcode实际上是一个整数,并且与值(将是字符串)分开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM