栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

mysql 存储过程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

mysql 存储过程

        将若干条sql语句封装起来,类似于函数。

--创建
create procedure 存储过程名([参数列表])
begin
    --sql语句
end;

--调用
call 存储过程名([参数列表]);

--查看
select * from information_schema.ROUTINES where ROUNTINE_SCHEMA = '某数据库名';    --查询指定数据库的存储过程及状态信息。
show create procedure 存储过程名;    --查询某个存储过程

--删除
drop procedure 存储过程名



delimiter $$;    --设置语句结束符为$$

系统变量:

show [session|global] variables;    --查看所有系统变量
show [session|global] variables like 'xxx';    --模糊查询
select [session|global] @@xxx    --查看系统变量的值
set [session|global] @@xxx = 值;    --更改系统变量的值

        全局变量:服务器恢复之后还会恢复原始值。想永久修改的话需要修改/etc/my.cnf

        会话变量:当前会话生效

用户变量:

        作用域为当前连接

set @变量名 = 值;

--使用
select @变量名;

局部变量:

        需要先声明

declare 变量名 变量类型[default ...];    --指定默认值
set 变量名 = 值;

if判断:

        if 条件 then ... else if 条件 then ... else ... end if;

参数:

        in、out、inout

create procedure p(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 p(18,@result);
select @result;

case when:

create procedure p1(in month int)
begin;
    declare result varchar(10);
    case
        when 条件表达式 then
            sql语句
        when 条件表达式 then
            sql语句
        else
            sql语句
    end case;
end;

循环:

--满足条件就循环
while 条件 do
    sql逻辑
end while

--满足条件就退出循环
repeat
    sql逻辑
    until 条件;
end repeat

--loop循环
sum:loop
    sql逻辑;
    iterate sum;    --跳过本次循环
    leave sum;    --结束循环
end loop sum;

cusor游标:用来存储查询结果集的数据类型

declare 游标名称 cursor for 查询语句;    --游标变量的声明,应当在普通变量之后
--使用游标之前必须打开游标
open 游标名;
fetch 游标名 into 字段1,字段2
close 游标名;

条件处理程序:

        抓到异常,执行处理

declare exit handler for SQLSTATE '02000' close 游标名    --SQLSTATE '02000'可以优化成not fund

存储函数:

        参数只能是in类型,需要声明返回值类型

create function 函数名(n int)
returns int deterministic   --声明返回值类型
begin
    sql逻辑
    return 3;
end;

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1020676.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号