存储过程和存储函数是事先经过编译并存储在数据库中的一段SQL语句的集合,调用存储过程和函数可以简化应用开发人员的工作,减少数据在数据库和应用服务器之间的传输,能够提高数据库的处理效率。
创建存储过程
create procedure 存储过程名称() begin sql语句集 end$ 改变语句结束符:delimiter 符号
调用存储过程
call 存储过程名称();
查看存储过程状态信息
show procedure status;
查询某个存储过程的定义
show create procedure 存储过程名称 \G
删除存储过程
drop procedure [if exists] 存储过程名称;
以下的步骤都必须写在(begin..end)中
定义变量
declare 变量名 数据类型 default (默认值);
变量赋值
set 变量名 = ‘值’; 或 select count(*) into 变量名 from 表名;
if条件判断
if 条件 then 执行语句; elseif 执行语句; then 执行语句; else 执行语句; end if; if exists(查询语句) then 执行语句; else 同上 判断查询语句是否查询出数据
传递参数
[in/out/inout] 参数名 参数类型 in:可输入 out:可输出 inout:可输入 可输出
inout模式
case结构(同 if)
等值判断: case 条件变量 when 值 then 执行语句; when 值 then 执行语句; else 执行语句; end case; 复合判断: case when 条件 and 条件 then 执行语句; when 同上 ... end case;
while循环(条件成立执行循环)
while 条件 do 执行语句; end while;
repeat结构(条件成立结束循环)
repeat 执行语句; until 条件 end repeat;
loop语句(利用leave关键字结束循环)
循环名称:loop 执行语句; end loop 循环名称; leave 循环名称;
游标/光标
声明光标(封装查询语句的结果集)
declare 光标名称 cursor for 查询语句;
打开光标
open 光标名称;
迭代游标(迭代一次,反馈一行数据)
fetch 光标名称 into 变量,变量,变量...;
关闭游标
close 游标名称;
declare has_data int default 1; declare exit handler for not found set has_data =0; 用法看上图
创建存储函数
create function 存储函数名称(参数 数据类型) returns 数据类型; begin sql语句集 return 变量; end$
调用存储函数
select 存储函数名称(传入值);
删除存储函数
drop function 存储函数名称;
存储过程和存储函数区别:存储函数有返回值。存储过程不可以用于select后。