MySql中的儲存過程和觸發器筆記
阿新 • • 發佈:2019-01-03
#表結構 CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(100) DEFAULT NULL, `user_type` tinyint(4) DEFAULT NULL, `user_password` varchar(50) DEFAULT NULL, `user_phone` varchar(12) DEFAULT NULL COMMENT, `user_pic` varchar(100) DEFAULT NULL COMMENT, `is_leave` tinyint(4) DEFAULT NULL COMMENT, `remark` varchar(500) DEFAULT NULL COMMENT, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='使用者表'; #===============建立一個簡單的儲存過程=============== create procedure helloworld() begin select * from `user`; select 'Hello World!' from dual; end; #呼叫儲存過程 call helloworld(); #刪除儲存過程 drop procedure if exists helloworld; #===============簡單的儲存過程(帶引數)=============== create procedure selectUserById(in p3 int) begin select * from `user` where id = p3; end; #呼叫儲存過程 call selectUserById(2); #刪除儲存過程 drop procedure if exists selectUserById; #===============簡單的儲存過程(使用遊標,帶引數)=============== create procedure selectUserByIdWithCursor(in p3 int) begin #申明遊標的值 declare not_found int default 0; #申明變數 declare _id int; declare name varchar(200) default ''; declare type int; declare password varchar(200); declare names varchar(200) default ''; #申明遊標 declare cursorName cursor for select id,user_name,user_type,user_password from `user` where id = p3; #對遊標的控制處理,當沒有找到為false declare continue handler for not found set not_found=0; #開啟遊標 open cursorName; #迴圈取值(使用loop迴圈) _loop:loop fetch cursorName into _id,name,type,password; if not_found=1 then leave _loop; end if; #輸出 select CONCAT(_id,name,type,password); end loop _loop; #關閉遊標 close cursorName; end; #呼叫儲存過程 call selectUserByIdWithCursor(0); #刪除儲存過程 drop procedure if exists selectUserByIdWithCursor; #===============簡單的觸發器()=============== create trigger checkUserType before insert on `user` for each row begin #如果插入使用者的型別錯誤 if new.user_type<0 then signal sqlstate 'HY000' set message_text = '手動丟擲異常' ; end if; end; #刪除觸發器 drop trigger if exists checkUserType;