MySQL觸發器簡單用法示例

2022-09-28 05:36:08 字數 1781 閱讀 7530

mysql觸發器和儲存過程一樣,是嵌入到mysql的一段程式,觸發器是由事件來觸發的,這些事件包括,insert,update,delete,不包括select

建立觸發器

create trigger name,time,event on table_name for each row trigger_stmt

例如複製** **如下:

create trigger ins_sum before insert on account for each row set @sum = @sum + new.amount

有多個執行語句的觸發器

create table test1(a1 int);

create table test2(a2 int);

create table test3(a3 int not null auto_increment primary key);

create table test4(

a4 int not null auto_increment primary key,

b4 int default 0

);delimiter //

create trigger testref before insert on test1

for each row begin

insert into test2 set a2 = new.a1;

delete from test3 where a3 = new.a1;

update test4 set b4 = b4 + 1 where a4 = new.a1;

end//

delimiter ;

insert into test3(a3) values (null), (null), (null), (null), (null), (null),(null), (null), (null), (null), (null), (null);

insert into test4(a4) values (0), (0), (0), (0), (0), (0), (0), (0), (0), (0);

//開始測試

insert into test1 values (1), (3), (1), (7), (1), (8), (4), (4);

檢視觸發器

show triggers \g; //檢視所有

select * from information_schema.triggers where trigger_name = 'testref';

刪除觸發器

drop trigger testref;

綜合案例

步驟1:建立poiztgkersons表

create table persons (name varchar(40), num int);oiztgk

步驟2:建立乙個銷售額表sales

程式設計客棧create tabl sales (name varchar(40), sum int);

步驟3:建立乙個觸發器

create trigger num_sum after insert 程式設計客棧on persons

for each row insert into sales values (new.name,7*new.num);

步驟4:向persons表中插入記錄

insert into persons values ('xiaoxiao',20),('xiaohua',69);

select * from persons;

select *from sales;

mysql 觸發器示例 MySQL觸發器示例 8

什麼是觸發器 需求 出於審計目的,當有人往表users插入一條記錄時,把插入的uid,uname,插入動作和操作時間記錄下來。delimiter create trigger tr users insert after insert onusersforeach rowbegin insert in...

mysql 觸發器示例

一些操作會觸發的函式。如更新 增刪改 rule hzq all 或 b rule table 表的時候,我們希望對更新操作做記錄。這種情況使用觸發器,使用者對 rule hzq all 有更新操作時,觸發記錄函式。create table update history bussiness varch...

Oracle觸發器簡單示例

首先建立兩張測試表 create table test t id number 4 t name varchar2 20 t age number 2 t char create table test log caozuo varchar2 20 tdate date 然後建立觸發器並且進行測試 c...