#表結構
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;