进阶07-存储过程

介绍

存储过程是事先经过编译并存储在数据库中的一段 SQL 语句的集合,调用存储过程可以简化应用开发 人员的很多工作,减少数据在数据库和应用服务器之间的传输,对于提高数据处理的效率是有好处的。

存储过程思想上很简单,就是数据库 SQL 语言层面的代码封装与重用。

基本语法

# 创建
create procedure p1()

begin
    select count(*) from stu;
end;

# 调用
call p1();

# 查看
select * from information_schema.ROUTINES where ROUTINE_SCHEMA = 'itcast';

show create procedure p1;

# 删除
drop procedure if exists p1;

变量

  1. 系统变量
  2. 用户自定义变量
  3. 局部变量

系统变量

系统变量 是MySQL服务器提供,不是用户定义的,属于服务器层面。分为全局变量(GLOBAL)、会话 变量(SESSION)。

-- 查看系统变量
show session variables;

show session variables like 'auto%';
show global variables like 'auto%';

select @@global.autocommit;
select @@session.autocommit;

-- 设置系统变量
set session autocommoit = 1;
set global autocommit = 0;

用户自定义变量

用户定义变量 是用户根据需要自己定义的变量,用户变量不用提前声明,在用的时候直接用 “@变量名” 使用就可以。其作用域为当前连接。

-- 赋值
set @myname = 'itcast';
set @myage := 10;
set @mygender := '男', @myhobby := 'java';

select count(*) into @mycount from tb_user;

-- 使用
select @myname, @myage, @mygender, @myhooby
select @mycolor , @mycount;
select @abc;

局部变量

局部变量 是根据需要定义的在局部生效的变量,访问之前,需要DECLARE声明。可用作存储过程内的 局部变量和输入参数,局部变量的范围是在其内声明的BEGIN … END块。

-- 声明局部变量 - declare
-- 赋值
create procedure p2()
begin 
        declare stu_count int default 0;
        select count(*) into stu_count from stu;
        select stu_count;
end;

call p2();

if

案例
根据定义的分数score变量,判定当前分数对应的分数等级。
score >= 85分,等级为优秀。
score >= 60分 且 score < 85分,等级为及格。
score < 60分,等级为不及格。

create procedure p3()
begin
    declare score int default 58;
    declare result varchar(10);
    if score >= 85 then
        set result := '优秀';
    elseif score >= 60 then
        set result := '及格';
    else
        set result := '不及格';
    end if;
    select result;
end;
call p3();

参数

  1. in:输入
  2. out:输出
  3. inout:输入输出

案例
根据传入参数score,判定当前分数对应的分数等级,并返回。
score >= 85分,等级为优秀。
score >= 60分 且 score < 85分,等级为及格。
score < 60分,等级为不及格。

create procedure p4(in score int, out result varchar(10))
begin
    if score >= 85 then
        set result := '优秀';

    elseif score >= 60 then
        set result := '及格';
    else
        set result := '不及格';
    end if;
end;

call p4(18, @result);
select @result;

将传入的200分制的分数,进行换算,换算成百分制,然后返回。

create procedure p5(inout score double)
begin
    set score := score * 0.5;
end;
set @score = 198;
call p5(@score);
select @score;

case

根据传入的月份,判定月份所属的季节(要求采用case结构)。
1-3月份,为第一季度 4-6月份,为第二季度 7-9月份,为第三季度 10-12月份,为第四季度

create procedure p6(in month int)
begin
    declare result varchar(10);
    case
        when month >= 1 and month <= 3 then set result := '第一季度';
        when month >= 4 and month <= 6 then set result := '第二季度';
        when month >= 7 and month <= 9 then set result := '第三季度';
        when month >= 10 and month <= 12 then set result := '第四季度';
        else set result := '非法参数';
        end case;
    select concat('您输入的月份为: ', month, ', 所属的季度为: ', result);
end;
call p6(16);

while

计算从1累加到n的值,n为传入的参数值。

create procedure p7(in n int)
begin
    declare total int default 0;

    while n > 0
        do
            set total := total + n;
            set n := n - 1;
        end while;
    select total;
end;

call p7(100);

repeat

repeat是有条件的循环控制语句, 当满足until声明的条件的时候,则退出循环 。
计算从1累加到n的值,n为传入的参数值。(使用repeat实现)

create procedure p8(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 p8(10);

loop

LOOP 实现简单的循环,如果不在SQL逻辑中增加退出循环的条件,可以用其来实现简单的死循环。
LOOP可以配合一下两个语句使用:
LEAVE :配合循环使用,退出循环。
ITERATE:必须用在循环中,作用是跳过当前循环剩下的语句,直接进入下一次循环。

案例一
计算从1累加到n的值,n为传入的参数值。  
create procedure p9(in n int)
begin
    declare total int default 0;

    sum:
    loop
        if
            n <= 0 then
            leave sum;
        end if;

        set total := total + n;
        set n := n - 1;
    end loop sum;

    select total;
end;

call p9(100);


案例二
计算从1到n之间的偶数累加的值,n为传入的参数值。
create procedure p10(in n int)
begin
    declare total int default 0;

    sum :
    loop
        if
            n <= 0 then
            leave sum;
        end if;

        if
            n % 2 = 1 then
            set n := n - 1;
            iterate sum;
        end if;

        set total := total + n;
        set n := n - 1;
    end loop sum;
    select total;
end;

call p10(100);

游标

游标(CURSOR)是用来存储查询结果集的数据类型 , 在存储过程和函数中可以使用游标对结果集进 行循环的处理。游标的使用包括游标的声明、OPEN、FETCH 和 CLOSE

create procedure p11(in uage int)
begin
    declare uname varchar(100);
    declare upro varchar(100);
    declare u_cursor cursor for select name, profession from tb_user where age <= uage;

    drop table if exists tb_user_pro;
    create table if not exists tb_user_pro
    (
        id         int primary key auto_increment,
        name       varchar(100),
        profession varchar(100)
    );

    open u_cursor;
    while true
        do
            fetch u_cursor into uname,upro;
            insert into tb_user_pro values (null, uname, upro);
        end while;
    close u_cursor;
end;

call p11(30);

条件处理程序

条件处理程序(Handler)可以用来定义在流程控制结构执行过程中遇到问题时相应的处理步骤。

create procedure p11(in uage int)
begin
    declare uname varchar(100);
    declare upro varchar(100);
    declare u_cursor cursor for select name, profession from tb_user where age <= uage;

    -- 声明条件处理程序 : 当SQL语句执行抛出的状态码为02000时,将关闭游标u_cursor,并退出
    declare exit handler for SQLSTATE '02000' close u_cursor;

    drop table if exists tb_user_pro;
    create table if not exists tb_user_pro
    (
        id         int primary key auto_increment,
        name       varchar(100),
        profession varchar(100)
    );

    open u_cursor;
    while true
        do
            fetch u_cursor into uname,upro;
            insert into tb_user_pro values (null, uname, upro);
        end while;
    close u_cursor;
end;

call p11(30);

也可以简写:
declare exit handler for not found close u_cursor;

存储函数

存储函数是有返回值的存储过程,存储函数的参数只能是IN类型的。

create function fun1(n int)
    returns int
    deterministic
begin
    declare total int default 0;
    while n > 0
        do
            set total := total + n;
            set n := n - 1;
        end while;
    return total;
end;
select fun1(50);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
存储过程是在数据库中预先定义的一组 SQL 语句集合,可以接受参数并返回结果。它们被封装在数据库服务器中,可以通过调用存储过程来执行这些 SQL 语句。 进阶的 SQL 存储过程技术包括以下几个方面: 1. 参数传递:存储过程可以接受输入参数,并根据这些参数执行相应的逻辑。参数可以是输入参数、输出参数或者既有输入又有输出的参数。使用参数可以使存储过程更加灵活和通用。 2. 流程控制:存储过程支持条件控制、循环和异常处理。条件控制可以根据不同的条件执行不同的 SQL 语句,循环可以重复执行某一段 SQL 语句,异常处理可以捕获并处理运行时发生的异常。 3. 事务处理:存储过程可以在一个事务中执行一组相关的 SQL 语句,并保证这些 SQL 语句要么全部执行成功,要么全部回滚。这样可以确保数据的一致性和完整性。 4. 数据库对象操作:存储过程可以创建、修改或删除数据库对象,例如表、视图、索引等。通过存储过程来操作数据库对象可以提高安全性和可维护性。 5. 动态 SQL:存储过程可以使用动态 SQL 语句,即在运行时构建 SQL 语句的字符串并执行。这样可以根据不同的条件生成不同的 SQL 语句,提高存储过程的灵活性。 6. 安全性:存储过程可以通过授权的方式实现访问控制,只有拥有相应权限的用户才能执行存储过程。这样可以保护数据库的安全性。 通过学习和掌握这些进阶存储过程技术,你可以更好地使用存储过程来实现复杂的业务逻辑和数据操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值