Mysql之存储过程

含义: 一组预先编译好的SQL语句的集合,可以理解成批处理语句
优点:
1、提高代码的重用性
2、简化操作
3、减少编译次数并且减少了和数据库服务器的连接次数,提高了效率

一、创建语法

create procedure 存储过程名(参数列表)
begin
    存储过程体(一组合法的SQL语句)
end

注意:
1、参数列表包含三部分
参数模式 参数名 参数类型
举例:
in student varchar(20)

参数模式:
in:该参数可以作为输入,也就是该参数需要调用方传入值
out:该参数可以作为输出,也就是该参数可以作为返回值
inout:该参数既可以作为输入又可以作为输出,也就是该参数既需要传入值,又可以返回值

2、如果存储过程体仅仅只有一句话,begin end可以忽略,存储过程体中的每条SQL语句的结尾要求必须加分号。
存储过程的结尾可以使用delimiter重新设置
语法:

delimiter 结束标记

调用语法

call 存储过程名(实参列表);

1、空参列表
案例:向表中插入3条数据

select * from collections

《Mysql之存储过程》

delimiter $
create PROCEDURE my1()
BEGIN
    insert into collections(user_id, quotation_id) 
VALUES(1,2),(3,4),(5,6);
end $

call my1(); // 调用存储过程

《Mysql之存储过程》

2、创建带in模式参数的存储过程
案例:创建存储过程实现,数据是否存在

delimiter $
create PROCEDURE my2(in user_id int, in quotation_id int)
BEGIN
    DECLARE result int default 0; // 声明并赋初值
    
    select count(*) into result from collections
    where collections.user_id = user_id
    and collections.quotation_id = quotation_id;
    select if(result>0,'存在','不存在');
end $

call my2(1,2)

《Mysql之存储过程》

3、创建带out模式参数的存储过程
案例:返回user_id对应的quotation_id的值

delimiter $
create PROCEDURE my3(in user_id int, out quotationId int)
BEGIN
    select collections.quotation_id into quotationId from collections
    where collections.user_id = user_id;
end $

call my3(1,@quoId); // 传入要返回的变量
select @quoId; // 输出变量的值

《Mysql之存储过程》
4、创建带inout模式参数的存储过程
案例:传入a和b两个值,最终a和b都翻倍并返回

delimiter $
create PROCEDURE my4(inout a int, inout b int)
BEGIN
    set a=a*2;
    set b=b*2;
end $
# 调用
set @m=10;
set @n=20;
call my4(@m, @n);
SELECT @m; // 20
SELECT @n; // 40

二、删除存储过程

#语法:drop procedure 存储过程名

三、查看存储过程

#语法:show create procedure 存储过程名
    原文作者:binbin
    原文地址: https://segmentfault.com/a/1190000020983601
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞