进阶篇05——存储过程、存储函数、触发器

存储过程

简介

基本语法

创建和调用

-- 创建名为p1的存储过程,小括号里可以跟参数
-- 存储过程个人觉得就是SQL里的函数
create procedure p1()
begin
    -- begin 和 end 之间是封装的SQL语句
    -- 可以是一条SQL也可以是多条SQL
    select * 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)
begin
    declare res varchar(10);
    case
        when 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)
begin
    declare sum int default 0;
    while n > 0 do
        set 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)
begin
    declare total int default 0;
    repeat
        set total := total + n;
        set n := n - 1;
        until n <= 0
    end repeat;
    select total;
end;

call p4(4);

loop 循环

-- 计算从1累加到n的值 loop 循环实现
drop procedure if exists p5;
create procedure p5(in n int)
begin
    declare total int default 0;
    total_n: loop
        -- 指定退出loop循环的条件
        if n <= 0 then
            leave 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)
begin
    declare total int default 0;
    total_n: loop
        if n <= 0 then
            leave 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 类型触发器

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值