如何创建更新触发器?

时间:2012-05-18 11:17:44

标签: mysql triggers

我有一个非常简单的问题,所以我希望有人会帮忙。

我有一个带ID和CREDIT的MySQL表。我想做一个更新触发器,如果​​credit为0,它会改变更新值。所以像“if old.CREDIT = 0 then new.CREDIT = 0.001”。那么触发器的语法是什么?感谢。

1 个答案:

答案 0 :(得分:1)

请阅读tutorial on MySQL Triggers,其中包含简单复杂的例子 以下是before update触发器的简单示例,可能对您有所帮助。

假设表名为credit_info

delimiter //
create trigger sample_trigger_before_update_on_credit_info before update on test.credit_info
  for each row begin
    if new.credit = 0 then
      set new.credit = 0.001;
    end if;
  end;
//
delimiter ;

我们说,表有2条记录如下:

+------+--------+
| id   | credit |
+------+--------+
|    1 |  1.000 |
|    2 |  3.000 |
+------+--------+

当您发布更新语句时:

update credit_info set credit=0 where id=2;

结果记录如下:

+------+--------+
| id   | credit |
+------+--------+
|    2 |  0.001 |
+------+--------+

让我希望,示例将加速你的精力。