MySQL 触发器

你离开我真会死。 提交于 2019-11-28 11:09:45

1、什么是触发器

  是用户定义在关系表上的一类由事件驱动的数据对象,也是一种保证数据完整性的方法。

 

2、创建触发器

-> create trigger mysql_test.customers_insert_trigger after insert
->on mysql_test.customers for each row set @str = 'one customer added'


//@str表示用户变量//这里表示有数据插入时  str变为one customers added

 

3、插入一条数据触发触发器

->insert into customers
->values(1001,"张三",19,"男");

->select @str;

//插入一条数据,改变了用户变量的值,我们应该直接查看用户变量,而不是原表

 

4、删除触发器

drop trigger if exists mysql_test.customers;

//删除一个触发器

 

5、触发器的种类

  insert 触发器

  delete触发器

  update触发器

insert触发器

在insert触发器代码内,可引用一个名为new(不区分大小写)的虚拟表,来访问被插入的行
在before insert触发器中,new中的值可以被跟新new即被插入的数据->create trigger mysql_test.customers_insert2 after insert->on mysql_test.customers for each row set @str = new.cust_id;//制定了触发器的触发规则->insert into customers->values("1002","李四",22,"男");//插入一行数据进行触发->select @str;//重新查看用户变量,查看是否被触发
delete触发器
在delete触发器代码内,可引用一个名为OLD(不区分大小写)的虚拟表,来访问被删除的行。
OLD中的值全部都是只读的,不能被更新。


->create trigger mysql_test.customers_delete after detele
->on mysql_test.customers for each row set @str = old.name;
//制定触发器规则

->delete from from mysql_test.customers
->where id = 1001;
//对触发器进行触发

->select @str;
//查看触发器
update触发器 = 先delete  后 insert
在update触发器代码内,可引用一个名为OLD(不区分大小写)的虚拟表,来访问update语句执行前的值,也可以引用一个名为new(不区分大小写)的虚拟表来访问跟新后的值。


->create trigger mysql_test.customers_update_trigger before update
->on mysql_test.customers  for each row
->set new.cust_address = OLD.cust_contact;//创建触发器规则

->update mysql_test.customers set cust_address = '武汉市'
->where cust_name = '曾伟';
->select cust_address from mysql_test.customers
->where cust_name = '曾伟';

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!