while...end while
loop ... end loop
repeat ... end repeat
goto(不推荐使用,流程混乱,淘汰)
create procedure p9()
begin
declare v int;
set v=0;
while v<5 do ---循环的入口(必须满足的条件)
insert into t1 values(v);
set v=v+1; ---循环的出口(退出循环的条件)
end while;
end//
call p9()//
select * from t1//
提醒:执行结束后的系统返回是针对最后一条insert语句
create procedure p10()
begin
declare v int;
set v=0;
repeat
inset into t1 values(v);
set v=v+1; ---出口条件
end repeat; ----入口条件
end//
call p10()//
select * from t1//
create procedure p11()
begin
declare v int;
set v=0;
loop_label:loop
insert into t1 values(v);
set v=v+1;
if v>5 then
leave loop_label;
end if;
end loop;
end//
删除存储过程
drop procedure 名;
select ...into 变量列表
只能应用在存储过程
create procedure p12(out paral char(20))
begin
select s1 into paral from t1;
end//
select 返回结果:表、列、行、值
游标(指针):
步骤:
创建游标:declare
打开游标:open
获取记录:fetch
关闭游标:close
1.select ...into
注意:into关键字后的变量要求先声明;
只能出现在存储过程和触发器,不能单独使用
字段(数量、类型)要和变量一致
只能针对一行;
返回标量值
练习1:针对db1中的tb1
把一个字段的内容保存到变量,显示该变量
搜索的结果为多条,移动指针
步骤:
创建游标;
打开游标;
获取记录;
关闭游标;
语法:
declare 游标名称 cursor for
select ...from ...where...; ---不能有into关键字
注意:声明完成后并不执行;
open 游标名称
fetch 游标名称 into 变量;
close 游标名称;
练习2:针对练习1
流程控制语句 while
循环次数无法确定,异常提示
语法:
异常代码:
SQLSTATE 代码
error 1022 xxxxxxxxx
参见手册(异常对应描述)
内置异常描述
declare exit handler for SQLSTATE 信息执行的动作
declare continue handler for SQLSTATE 信息执行的动作
注意:
1.执行顺序(声明位置无要求,建议在开头,当错误出现的时候被执行)
如果是exit类型的在终止整个存储过程的执行;
如果是continue类型的在出现错误的位置继续执行
2.条件
自定义异常描述
修改存储过程:删除后重写(自己练习)