Mysql触发器实例

来源:互联网 发布:五十知天命的意思 编辑:程序博客网 时间:2024/05/01 09:12

任务描述:

有2张表:

表1:device, 里面有最主要的2个字段(id, device_type, .....),表明了"设备类型"与"ID";

表2:alarm_information,记录了每种设备的告警信息,其中有2个主要字段(id, device_type, ....);

 

要求:当 device中的某项被删除的时候,alarm_information中该设备所有的告警信息全部被删除。

 

在device中创建触发器:

///////////////////////////////////////////////////////////////////////////////////////////////

create   trigger   update_alarm_information   before delete   on   device   
  for   each   row  

begin    
  set   @id=OLD.id; //保存被删除设备的“id”

  set   @dtype=OLD.device_type;  //保存被删除记录的“device_type”
  delete   from   alarm_information   where   id=@id and device_type = @dtype;   
end;

///////////////////////////////////////////////////////////////////////////////////////////////

 

如果用Navicat for Mysql创建触发器就更加方便了

  1. 首先选择表device,点击右键,在弹出菜单中选择“设计表”
  2. 选择“触发器”

3.  在定义框中写入:

begin    
  set   @id=OLD.id; //保存被删除设备的“id”

  set   @dtype=OLD.device_type;  //保存被删除记录的“device_type”
  delete   from   alarm_information   where   id=@id and device_type = @dtype;   
end;

4.  完成

原创粉丝点击