MySQL中觸發器

2021-08-03 20:29:32 字數 1990 閱讀 7144

觸發器是與某個事件相關的特殊儲存過程,與儲存過程不同的是,儲存過程需要用 call 呼叫而出發器不需要使用call呼叫呼叫。

也就是自己預先定義好了,當某個事件發生時,就會自動出發觸發器進行相關的操作。

僅對 insert 、 update 、delete 有效,對select無。

trigger_name :觸發器名字,其實這個為了便於對觸發器的修改與刪除而存在。

trigger_time:觸發事件,在事件觸發前執行還是出發後執行。

tigger_action:觸發的動作。

listen_object:監聽物件。

listen_action:監聽的動作。

create trigger trigger_name  trigger_time  listen_action  on   listen_object

for each row

begin

trigger_action;

eng$

注意:由於mysql預設的是 ; 為語句結束符,因此在這裡需要修改,我修改為$:delimeter  $。

訂單是原先沒有的,如果觸發器的事件要引用新新增的訂單的資訊,那麼就要用 new.列明,進行引用資料。

create

trigger order_shop after insert

on `order

`for

each row

begin

update shop set shop_count = shop_count-new.order_count where shop_id =

new.shop_id;

end$

create

trigger delete_order before delete

on `order

`for

each row

begin

update shop set shop_count = shop_count+old.order_count where shop_id =

old.shop_id;

end$

注意:這裡引用資料是使用 old.列明 ,原因在於引用的資料是已經存在了,所以用old

create

trigger change_order after update

on `order

`for

each row

begin

update shop set shop_count = shop_count+old.order_count - new.order_count where shop_id =

new.shop_id;

end$

注意:這裡都用到了old和new關鍵字,讓庫存加上原來的資料再減去新資料。

show triggers;

after  是 先完成資料的增刪改再觸發

before  是 先完成觸發在再增刪改。  eg:限購

例如:沒人僅限購五件商品,大於5的都設為5

create

trigger example_before before insert

on `order

`for

each row

begin

if new.order_count>

5then

set new.order_count =

5;

endif

;update shop set shop_count = shop_count-new.order_count where shop_id =

new.shop_id;

end$

觸發器 mysql觸發器

觸發器是一種特殊的儲存過程,它在插入 刪除或修改特定表中的資料時觸發執行,它比資料庫本身標準的功能有更精細和更複雜的資料控制能力。和儲存過程一樣,很少使用。1 觸發器的作用 2 建立觸發器 建立測試環境 mysql create database test db query ok,1 row aff...

my sql 觸發器 mysql建立觸發器

首先,我們來了解一下什麼是觸發器,觸發器,就是在對一張表資料進行增 insert 刪 delete 改 update 的時候,為了保持資料的一致性,對別的表也要進行相應的資料修改。我們都知道mysql最後事務提交後,資料是會儲存到磁碟上的,那麼每次在insert,delete,update時候舊資料...

my sql 觸發器 MySQL檢視觸發器

檢視觸發器是指檢視資料庫中已經存在的觸發器的定義 狀態和語法資訊等。mysql 中檢視觸發器的方法包括 show triggers 語句和查詢 information schema 資料庫下的 triggers 資料表等。本節將詳細介紹這兩種檢視觸發器的方法。show triggers語句檢視觸發器...