(mysql)触发器trigger

(1)
Trigger是数据库中的事件触发,当前MySQL的实现是对特定table的DML语句(INSERT/UPDATE/DELETE)调用时触发.
(2)
格式:
CREATE [DEFINER={user|CURRENT_USER}] TRIGGER trigger_name
  {BEFORE|AFTER}
  {INSERT|UPDATE|DELETE}
ON table_name
FOR EACH ROW
trigger_statements
(3)
查看触发器的命令:
show triggers ;
也可用 show triggers \G
重要说明:
procedure,function,trigger的查看显示,可以在原来的基础上加参数 \G来简洁显示内容.如下:
procedure: show procedure status \G 或 show create procedure ** \G
function: 同上.
trigger: show triggers \G
(4)
4.1
AFTER类型的Trigger,不能修改NEW记录的值
4.2
如果同时对大量的行做操作,Trigger可能性能开销较大,所以尽量避免在Trigger里放入性能消耗大的SQL语句 .
(5)
实例一:
delimiter //
create trigger beforeupdatecustomer
before update on customer
for each row
begin
create temporary table tempa select * from customer;
end //
实例二:
从以下的实例可见:
触发器的作用是: 用于管理数据库中有关系的表.
/*先删除将要创建而存在的表*/
drop table if exists Student;
drop table if exists BorrowStudent;
/*创建表*/
create table Student(
StudentID int not null primary key,
StudentName varchar(30) not null,
StudentSex enum('m','f') default 'm'
)engine=myisam;
create table BorrowStudent(
BorrowRecord int not null auto_increment primary key,
StudentID int not null,
BorrorDate date,
ReturnDate date,
foreign key(StudentID) references Student(StudentID)
)engine=myisam;
/*插入记录*/
insert into Student values(1235412,'java','m');
insert into Student values(3214562,'jiajia','m');
insert into Student values(5441253,'purana','f');
insert into BorrowStudent(StudentID,BorrorDate,ReturnDate)
values(1235412,'2007-01-01','2007-01-07');
insert into BorrowStudent(StudentID,BorrorDate,ReturnDate)
values(3214562,'2007-01-01','2007-01-07');
insert into BorrowStudent(StudentID,BorrorDate,ReturnDate)
values(5441253,'2007-01-01','2007-01-07');
/*创建触发器*/
delimiter $$
drop trigger if exists tduStudent$$
drop trigger if exists tddStudent$$
create trigger tduStudent before update
on Student for each row
begin
/*
new.触发器作用表的某字段名:表示修改后的字段值;
old.触发器作用表的某字段名:表示修改前的字段值;
*/
if new.StudentID!=old.StudentID then   -- 意思是:当表studentID发生变化时,执行
update BorrowStudent
set BorrowStudent.StudentID=new.StudentID
where BorrowStudent.StudentID=old.StudentID;
end if;
end$$
create trigger tddStudent before delete
on Student for each row
begin
delete
from BorrowStudent
where BorrowStudent.StudentID=old.StudentID;
end$$
delimiter ;

本文出自 “Changes we need ! ” 博客,转载请与作者联系!

你可能感兴趣的:(mysql,数据库,职场,休闲)