MySql-使用触发器(trigger)

来源:互联网 发布:毒药超女网络海选 编辑:程序博客网 时间:2024/05/16 08:37
需求说明:
有一张员工表fdp_users,有一张绩效表fdp_user_performance,当修改员工表数据时,想同步对绩效表做修改,所以使用触发器来处理这种小事。

SQL语法:
create trigger trigger_name AFTER/BEFORE INSERT/UPDATE/DELETE on table_name FOR EACH ROW
begin
sql
end


关键字说明(来自官网):

The keyword AFTER/BEFORE indicates the trigger action time. 

The keyword INSERT/UPDATE/DELETE indicates the trigger event; that is, the type of operation that activates the trigger. 

The statement following FOR EACH ROW defines the trigger body; that is, the statement to execute each time the trigger activates, which occurs once for each row affected by the triggering event.

例子:
1. 用户表新增一条数据后,绩效表也新增一条数据,committer字段就是用户表的svn_name字段
create trigger tri_insert_performance after insert on fdp_users for each rowbegin     insert into fdp_user_performance(committer,create_date,modified_date) values(new.svn_name,sysdate(),sysdate());end;
这里的new就代表了新数据(也就是users表新增数据)


2. 用户表删除一条数据后,绩效表也把这个人的信息删除
create trigger tri_delete_performance after delete on fdp_users for each rowbegin    delete from fdp_user_performance where committer = old.svn_name;end;
这里的old就代表了刚刚users表删除的数据


3. 用户表更新一条数据后,绩效表也把这个人的数据更新
create trigger tri_update_performance after update on fdp_users for each rowbegin    update fdp_user_performance set committer = new.svn_name where committer = old.svn_name;end;
这里的new代表了users表新修改后的数据,old代表了修改前的旧数据

========================昏割线==========================

其他SQL:

查看现有的触发器:

show triggers;


删除触发器:

drop trigger trigger_name;
0 0