此文章是我初学Mysql编程的时候做的一些总结。
过程--procedure
1.在php 中,是没有过程(procedure)这个概念的,php只有函数(function)概念
过程:没有返回值得函数
函数:一个有返回值的过程
2.存储过程:把若干条sql语句封装起来==>过程
我们把这个过程储存在数据库中==>储存过程
3.创建语法:
create procedure p12()
begin
sql....
end$
查看已有的过程: show procedure status
删除已有的过程: drop procedure p2 //不需要加()
调用储存过程: call p1()
4.储存过程是可以编程的
可以使用变量,表达式、控制结构、来完成复杂的控制
1.声明变量
使用 declare 来声明变量 //类似于sql中创建列
而且变量可以进行合法的运算 */-+
格式
create procedure p3()
begin
declare age int default 18; // 声明int型变量 age。默认18
set age := age + 20; //把age+20的运算结果赋给age
// := 是赋值的意思
select concat('年龄是', age);//select 表示输出的意思
end$
2.可以有变量控制结构 (顺序、选择、循环)
if/else
结构
create procedure p4()
begin
declare age int default 18;
if age>18 then
select '成年';
else
select '未成年';
end$
while/do
结构
create procedure p5()
begin
declare total int default 0;
declare num int default 0;
while num<=100 do
set total := total+num;
set num := num+1;
end while;
select total;
end$
case 多条件分支
结构
create procedure p11()
begin
declare pos int default 0;
set pos := floor(5*rand());
case pos
when 1 then select '1111111';
when 2 then select '2222222';
when 3 then select '3333333';
else select '4444444';
end case;
end$
repeat 循环
结构
create procedure p12()
begin
declare total int default 0;
declare i int default 0;
repeat
set i := i + 1;
set total := total + i;
until i>=100 end repeat;
select total;
end$
3.声明参数(传参)
in/out/inout
(in 表示从窗口输入到程序中)
(out 表示输出)
in 的结构
create procedure p8(in n int) //in 表示这个参数要输入到过程中 out 表示向外发射一个值
begin
declare total int default 0;
declare num int default 0;
while num<n do
set num := num+1;
set total := total+num;
end while;
select total;
end$
out 的结构
create procedure p9(in n int, out total int)
begin
declare num int default 0;
declare total int default 0; //必须要有初始值,否则total为null,null和任何数组合都为null
while num < n do
set num := num+1;
set total := total+num;
end while;
end$
--在窗口内输入 call p9(100, @sum)
--然后在输入 select @sum
inout 的结构
create procedure p10(inout age int)
begin
set age := age +20;
end$
-- 在黑窗口中输入
-- set @currage = 8
-- call p10(@currage)
-- select @currage