存储过程
简介


基本语法
创建和调用

-- 创建名为p1的存储过程,小括号里可以跟参数
-- 存储过程个人觉得就是SQL里的函数
create procedure p1()
begin-- begin 和 end 之间是封装的SQL语句-- 可以是一条SQL也可以是多条SQLselect * from student;
end;-- 调用存储过程
call p1();
查看和删除

-- 查看存储过程
# 方式一
select * from information_schema.ROUTINES where ROUTINE_SCHEMA = 'test1';# 方式二
show create procedure p1;-- 删除存储过程
drop procedure if exists p1;


MySQL中的变量
系统变量


用户自定义变量


局部变量


条件判断
if


case

-- 根据输入的月份判断为第几季度
drop procedure if exists p2;
create procedure p2(in month int)
begindeclare res varchar(10);casewhen month between 1 and 3 then set res := '第一季度';when month between 4 and 6 then set res := '第二季度';when month between 7 and 9 then set res := '第三季度';when month between 10 and 12 then set res := '第四季度';else set res := '输入值不正确';end case;select concat('输入的月份', month, '所属的季度为', res);
end;call p2(6);
存储过程的参数



循环
while 循环

-- 计算从1累加到n的值 while 循环实现
drop procedure if exists p3;
create procedure p3(in n int)
begindeclare sum int default 0;while n > 0 doset sum := sum + n;set n := n - 1;end while;select sum;
end;call p3(3);
repeat 循环

-- 计算从1累加到n的值 repeat 循环实现
drop procedure if exists p4;
create procedure p4(in n int)
begindeclare total int default 0;repeatset total := total + n;set n := n - 1;until n <= 0end repeat;select total;
end;call p4(4);
loop 循环

-- 计算从1累加到n的值 loop 循环实现
drop procedure if exists p5;
create procedure p5(in n int)
begindeclare total int default 0;total_n: loop-- 指定退出loop循环的条件if n <= 0 thenleave total_n;end if;set total := total + n;set n := n - 1;end loop total_n;select total;
end;call p5(5);-- 计算从1累n中偶数的累加值 loop 循环实现
drop procedure if exists p6;
create procedure p6(in n int)
begindeclare total int default 0;total_n: loopif n <= 0 thenleave total_n;elseif n % 2 != 0 then-- 注意,这里要记得把 n 的值减一set n := n - 1;iterate total_n;end if;set total := total + n;set n := n - 1;end loop total_n;select total;
end;call p6(6);
游标




存储函数


触发器
基本介绍

基本语法

案例
insert 类型触发器
update 类型触发器
更新表tb_user的数据时会自动触发该触发器的执行

delete 类型触发器

