储存过程
前提: 在大型数据库中
定义: 储存在数据库中, 用户通过指定储存过程的名字并给出参数 (带有参数的) 来执行它
声明: 储存过程是数据库中一个重要的对象, 类似于 PHP,js 中的函数
创建储存过程
create procedure 名称(in|out|inout 名称 类型,...)
begin
过程体;
end
说明: 过程体可以使用所学的所有 SQL
可以运用变量, 运算, 流程控制语句, 函数
储存过程没有返回值
in 传入参数
out 传出参数
inout 传入传出参数
储存过程中的变量
数据类型
int smallint tinyint char varchar text enum() set() 等
声明变量
declare 变量名 类型(长度)
default 默认值
变量赋值
set 变量名 = 值
变量使用
变量名
储存过程中的运算
算数运算
+ - */ %
比较运算
> <>= <= = != <>
逻辑运算
and or not
赋值
set 变量 = 值
储存过程中的条件语句
if 条件 then
elseif 条件 then
过程;
elseif 条件 then
过程;
elseif 条件 then
过程;
else
过程;
end if;
储存过程中选择语句
case 变量名或字段或表达式
when 0 then
语句;
when 1 then
语句;
else
语句;
end case;
储存过程中循环语句
while 循环条件 do
变换步长;
- end while;
- repeat
变换步长
until 终止条件
end repeat;
储存过程中的函数
字符串函数:
- CONCAT (string2 [,... ]) // 连接字串
- REPLACE (str ,search_str ,replace_str ) // 在 str 中用 replace_str 替换 search_str
- SUBSTRING (str , position [,length ]) // 从 str 的 position 开始, 取 length 个字符
数学函数:
- CEILING (number2 ) // 向上取整
- FLOOR (number2 ) // 向下取整
- RAND([seed]) // 随机数
- ROUND (number [,decimals ]) // 四舍五入, decimals 为小数位数]
时间日期函数:
- CURRENT_DATE ( ) // 当前日期
- CURRENT_TIME ( ) // 当前时间
- NOW ( ) // 当前时间
- CURRENT_TIMESTAMP ( ) // 当前时间
储存过程的管理
查看所有存储过程
select name from mysql.proc where db = 'system' and type= 'PROCEDURE'
查看某个存储过程
show create procedure 存储过程名称;
删除存储过程
drop procedure 存储过程名称;
来源: https://www.cnblogs.com/chenliuxiao/p/9328170.html