存储过程(Stored Procedure)是一组为了完成特定功能的SQL语句集,经编译后存储在数据库中,用户通过指定存储过程的名字并给定参数(如果该存储过程带有参数)来调用执行它。存储过程类似于函数。
变量作用域:1:局部变量(在begin和end之间用declare声明) declare 变量名 数据类型;
2:用户变量(@变量名 只对当前用户有效)
3:会话变量(连接过程有效)
4:全局变量
存储过程的创建:
create procedure 存储名([参数列表])
begin
sql语句;(注意分号结尾)
end
[参数列表]:
输入:in 参数名 参数类型(默认为输入)
输出:out 参数名 参数类型
输入输出:inout
注意:表名不可通过参数传递
存储过程的查看:
show procedure status where db='数据库名字'
存储过程的调用:
call 存储名
存储过程的删除:
drop procedure 存储名
方法:ifnull(exp1,exp2) exp1为null返回exp2,否则返回exp1
if判断:
if 条件表达式 then sql语句集;
elseif 条件表达式 then sql语句集;
[else sql语句集] ;
end if ;
注意:elseif中间没有空格
循环:
1:while循环
begin
DECLARE i int DEFAULT 1;
declare sum int DEFAULT 0;
while i<num DO
set num = num +i;
set i = i+1;
end while;
END
2:repeat
begin
DECLARE i int DEFAULT 1;
declare sum int DEFAULT 0;
repeat
set sum = sum +i;
set i = i+1;
until i>num end repeat;
select sum from dual;
END
3:loop
begin
DECLARE i int DEFAULT 1;
declare sum int DEFAULT 0;
begin_loop:LOOP
set sum = sum+i;
set i=i+1;
if i>num then leave begin_loop; end if;
end loop begin_loop;
select sum from dual;
END