本樣本實現如下效果:
0.test資料庫有userinfo使用者資訊表 和userinfolog使用者資訊日誌表
1.建立一個userinfo表新增記錄時的觸發器 將新增日誌加入到userinfolog
2.建立一個向userinfo表新增記錄的預存程序
3.根據userinfo表的出生日期欄位 我們將建立一個簡單算得年齡的自訂函數
4.建立一個userinfo的視圖 調用年齡函數
-------------
0.準備相關表
mysql> use test;
mysql> create table userinfo(userid int,username varchar(10),userbirthday date);
mysql> create table userinfolog(logtime datetime,loginfo varchar(100));
mysql> describe userinfo;
1.觸發器
mysql> delimiter |
mysql> create trigger beforeinsertuserinfo
-> before insert on userinfo
-> for each row begin
-> insert into userinfolog values(now(),CONCAT(new.userid,new.username));
-> end;
-> |
mysql> delimiter ;
mysql> show triggers;
2.預存程序
mysql> delimiter //
mysql> create procedure spinsertuserinfo(
-> puserid int,pusername varchar(10)
-> ,puserbirthday date
-> )
-> begin
-> insert into userinfo values(puserid,pusername,puserbirthday);
-> end;
-> //
mysql> show procedure status like 'spinsertuserinfo';
mysql> call spinsertuserinfo(1,'zhangsan',current_date);
mysql> select * from userinfo;
3.自訂函數
mysql> update userinfo
-> set userbirthday='2000.01.01'
-> where userid='1';
mysql> drop function if exists fngetage;
mysql> delimiter //
mysql> create function fngetage(pbirthday date)
-> returns integer
-> begin
-> return year(now()) - year(pbirthday);
-> end
-> //
4.視圖
mysql> create view viewuserinfo
-> as select * ,fngetage(userbirthday) as userage from userinfo;
mysql> select * from viewuserinfo;
清除日誌記錄
mysql> truncate table userinfolog;
mysql> delete from userinfolog;
本文轉摘自『藍派網』http://www.lan27.com/Article/200807/7557.htm