mysql> \d // 改变命令行下的结束符标志
mysql> create procedure p3()
-> begin
-> set @i=1; # 这样也可以定义变量变给值
-> while @i<10000 do
-> insert into t3 values (@i);
-> set @i=@i+1;
-> end while;
-> end //
1.存储过程创建语法
create procedure 存储过程名称()
begin
-- sql语句
end;
2.查看已有的存储过程
show procedure status;
3.调用存储过程
call 存储过程名称();
4.在存储过程中申明变量 declare
--格式 declare 变量名 变量类型 [default 默认值]
create procedure p2()
begin
declare age smallint default 18;
declare hi int smallint default 180;
select concat('年龄是:',age,'身高为:',hi);
end;
--运算和赋值
-- set 变量名 := expression
create procedure p3()
begin
declare age smallint default 18;
declare hi int smallint default 180;
set age := age+20;
select concat('年龄是:',age,'身高为:',hi);
end;
-- if/else控制结构
/**
if condition then
执行语句
else
end if;
*/
create procedure p4()
begin
declare age smallint default 18;
declare hi int smallint default 180;
if age>=18 then
select '成年';
else
select '很小';
end if;
end;
-- 存储过程传参
/**
存储过程的括号里,可以声明参数
语法[in/out/inout] 参数名 参数类型
*/
create procedure p5(width int,height int)
begin
select width+height;
end;
call p5(10,20);
--循环
--求1到100之和
create procedure p6()
begin
declare sum smallint default 0;
declare i smallint default 0;
while i<=100 do
set sum := sum+i;
set i := i+1;
end while;
select sum;
end;
call p6();
create procedure p7(in n int)
begin
declare sum smallint default 0;
declare i smallint default 0;
while i<=n do
set sum := sum+i;
set i := i+1;
end while;
select sum;
end;
call p7(100);
-- out 类型参数
create procedure p8(in n int,out total int)
begin
declare num int default 0;
set total := 0;
while num<n do
set num := num+1;
set total := total+num;
end while;
end;
call p8(100,@sum);
select @sum;
--inout类型
create procedure p9(inout age int)
begin
set age := age+20;
end;
set @currAge = 18;
call p9(@currAge);
select @currAge;
-- case用法
create procedure p10()
begin
declare pos int default 0;
set pos := floor(5*rand());
case pos
when 1 then select '小明';
when 2 then select '小华';
when 3 then select '小张';
else select '未知';
end case;
end;
call p10();
-----repeat 循环
/*
repeat
sql语句;
.....
sqlN;
until condition end repeat;
*/
create procedure p11()
begin
declare i int default 0;
declare sum int default 0;
repeat
set i := i+1;
set sum := sum+i;
until i>=100 end repeat;
select sum;
end;
##########################################################
1.查看存储过程
show procedure status;
2.删除存储过程
drop procedure 存储过程名称
3.创建存储过程
create procedure p1()
begin
select * from table;
end; call p1(); create procedure p2(n int)
begin
select * from table where num>n;
end; call p2(2); create procedure p3(n int,j char(1))
begin
if j='a' then
select * from table where num>n;
else
select * from table where num<n;
end if;
end; call p3(2,'a'); #计算1->n的和
create procedure p4(n smallint)
begin
declare i int;
declare sum int;
set i = 1;
set sum = 0;
while i <= n do
set sum = sum+i;
set i = i+1;
end while;
select sum;
end;
call p4(100);
4.调用存储过程
call 存储过程名称();