#表结构
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;
MySql中的存储过程和触发器笔记
猜你喜欢
转载自blog.csdn.net/qq_35341771/article/details/82687306
今日推荐
周排行