如何创建MySQL触发器?

时间:2012-02-24 11:04:21

标签: mysql triggers

有人可以帮我解决MySQL触发器

假设我有两张桌子

Table_Current
No (INT TYPE)
Name (VARCHAR TYPE)
Value (DECIMAL TYPE)

Table_Record
No (INT TYPE)
Name (VARCHAR TYPE)
Value (DECIMAL TYPE)

所以我想要实现的是,我在Table.Current上执行replace语句,如果字段'Value'的值小于Table.Record中的值,我想更新Value的值Table.Record,

以下是我作为触发器的内容

DELIMITER $$

CREATE TRIGGER Mytrigger
AFTER INSERT ON Table_Current

FOR EACH ROW
BEGIN

DECLARE CB DECIMAL (6,3);
DECLARE OB DECIMAL (6,3);

OB = SELECT Value FROM Table_Record WHERE Name=NEW.Name;
CB = NEW.Value;
IF CB<OB THEN
UPDATE Table_Record SET Value = NEW.Value WHERE Name = NEW.Name;
END IF;

END $$
DELIMITER;

1 个答案:

答案 0 :(得分:2)

你可以大规模地简化这个。你要做的是有效的查询

    UPDATE Table_Record

    SET `Value` = NEW.`Value` 
    WHERE `Name` = NEW.`Name`
    AND `Value` < NEW.`Value`;

您有兴趣更新Table_RecordName = NEW.Name的行。如果NEW.Value大于当前存储的-- First of all, drop any other trigger with the same name DROP TRIGGER IF EXISTS `Mytrigger`; -- Create the new trigger DELIMITER $$ CREATE TRIGGER `Mytrigger` AFTER INSERT ON Table_Current FOR EACH ROW BEGIN UPDATE Table_Record SET `Value` = NEW.`Value` WHERE `Name` = NEW.`Name` AND `Value` < NEW.`Value`; END $$ DELIMITER; ,您只想更新。因此,如果不满足该值约束,则不会更新上述内容。

此触发器代码应该执行您要实现的目标。

{{1}}