我有一个触发器,用于检查更新期间某些字段是否发生了变化。 如果这些字段中的任何一个发生了变化,我会更新另一个表。
一旦我知道某些事情发生了变化,我就想“打破”if条件。
有没有办法在MySQL触发器中执行此操作?
我的作品,但似乎效率低下。
CREATE TRIGGER profile_trigger
BEFORE UPDATE ON profile
FOR EACH ROW
BEGIN
DECLARE changed INTEGER;
SET changed = 0;
IF STRCMP(NEW.first_name, OLD.first_name) <> 0 THEN
SET changed = 1;
ELSEIF STRCMP(NEW.last_name, OLD.last_name) <> 0 THEN
SET changed = 1;
ELSEIF STRCMP(NEW.maiden_name, OLD.maiden_name) <> 0 THEN
SET changed = 1;
ELSEIF STRCMP(NEW.suffix, OLD.suffix) <> 0 THEN
SET changed = 1;
ELSEIF STRCMP(NEW.title, OLD.title) <> 0 THEN
SET changed = 1;
ELSEIF STRCMP(NEW.gender, OLD.gender) <> 0 THEN
SET changed = 1;
ELSEIF STRCMP(NEW.street, OLD.street) <> 0 THEN
SET changed = 1;
ELSEIF STRCMP(NEW.street2, OLD.street2) <> 0 THEN
SET changed = 1;
ELSEIF STRCMP(NEW.city, OLD.city) <> 0 THEN
SET changed = 1;
ELSEIF STRCMP(NEW.state, OLD.state) <> 0 THEN
SET changed = 1;
ELSEIF STRCMP(NEW.zip, OLD.zip) <> 0 THEN
SET changed = 1;
ELSEIF STRCMP(NEW.home_phone, OLD.home_phone) <> 0 THEN
SET changed = 1;
ELSEIF NEW.date_of_birth <> OLD.date_of_birth THEN
SET changed = 1;
END IF;
IF changed > 0 THEN
update other_table set updated = CURRENT_TIMESTAMP where id = NEW.id;
END IF;
END;
|
答案 0 :(得分:5)
这就是ELSEIF
本身的工作方式。一旦MySQL找到任何通过的条件(即,计算结果为TRUE),它将不会评估IF..ELSEIF..ELSE链中的任何其他条件。
答案 1 :(得分:2)
尝试CASE声明......
SET changed = CASE
WHEN STRCMP(NEW.first_name, OLD.first_name) <> 0 THEN 1
WHEN STRCMP(NEW.last_name, OLD.last_name) <> 0 THEN 1
WHEN STRCMP(NEW.maiden_name, OLD.maiden_name) <> 0 THEN 1
...
ELSE 0
END
答案 2 :(得分:1)
一个怪物OR
怎么样?它只意味着一个if语句;)
IF STRCMP(NEW.first_name, OLD.first_name) <> 0 or
STRCMP(NEW.last_name, OLD.last_name) <> 0 or
STRCMP(NEW.maiden_name, OLD.maiden_name) <> 0 or ...
...
SET changed = 1;
end if;
IF changed > 0 THEN
update other_table set updated = CURRENT_TIMESTAMP where id = NEW.id;
END IF;
......但是说真的,你的代码很好。没什么好担心的。 VoteyD是对的。
清除它的唯一方法是删除其中一些条件 - 尽管它可能不是一种选择。