一、觸發器
1.觸發器在數據庫里以獨立的對象存儲,
2.觸發器不需要調用,它由一個事件來觸發運行
3.觸發器不能接收參數
--觸發器的應用
舉個例子:校內網、開心網、facebook,當你發一個日志,自動通知好友,其實就是在增加日志的時候做一個出發,再向表中寫入條目。
--觸發器的效率很高
舉例:論壇的發帖,每插入一個帖子都希望將版面表中的最后發帖時間,帖子總數字段進行同步更新,這時使用觸發器效率會很高。
二、Oracle 使用 PL/SQL 編寫觸發器
1.--PL/SQL創建觸發器的一般語法
create [or replace] trigger trigger_name{before | after}{insert | delete | update [of column[,column ... ]]} on table_name[for each row][where condition]--trigger_body;begin end;
2.--練習
--問題3.使用:old 和 :new 操作符create or replace trigger tri_updateafterupdate on employeesfor each row begin dbms_output.put_line('更新前:'||:old.salary||' 更新后:'||:new.salary);end;--問題2.編寫一個觸發器,在向 emp 表中插入記錄時 打印'hello'create or replace trigger tri_updateafterinsert on empbegin dbms_output.put_line('ok');end;--問題1.一個helloworld級別的觸發器--創建一個觸發器,在更新employees表的時候觸發create or replace trigger tri_updateafterupdate on employeesfor each row --想在最后執行完打印一個ok,把這句話去掉begin dbms_output.put_line('ok');end;--執行update employeesset salary = salary+1where department_id = 80
三、在MySql 使用觸發器
--假設有兩張表 board 和 articlecreate table board( id int primary key auto_increment, name varchar(50), articleCount int);create table article( id int primary key auto_increment, title varchar(50), bid int references board(id));--創建一個觸發器delimiter $$create trigger insertArticle_trigger after insert on article for each rowbegin update board set articleCount=articleCount+1where id = new.bid;end;$$delimiter ;--當我們對article表執行插入操作的是后就會觸發這個觸發器insert into board values(null,'test_boardname',0);insert into article values(null,'test_title',1);--執行完這條插入語句后,board表中的articleCount字段值回+1;這個操作由觸發器完成。
以上所述是小編給大家介紹的Oracle使用觸發器和mysql中使用觸發器的案例比較,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VeVb武林網網站的支持!
新聞熱點
疑難解答