此篇为关于介绍SQL存储过程介绍的下篇,如有需要同学可以根据 上一篇结合这一篇,通透理解关于sql存储过程的理解,希望可以帮到大家,万分感激。
目录
1.8 case
1.9 循环 while
2.0 循环-repeat
2.1 循环-loop
2.2 游标-cursor
语法一:
CASE case_value
WHEN when_value1 THEN statement_list1
[WHEN when_value2 THEN statement_list2]...
[ELSE statement_list]
END CASE;
语法二:
CASE
WHEN search_condition1 THEN statement_list1
WHEN search_condition2 THEN statement_list2...
[ELSE statement_list]
END CASE;
案例:
根据传入的月份,判定月份所属 的季节(要求采用case结构)
1-3月份,第一季度
4-6月份,第二季度
7-9月份,第三季度
1.-12月份,第四季度
代码实现:
create procedure p6(in month int )
begin
declare result varchar(10);
case
when month>=1 and month<=3 then
set result:='第一季度';
when month>=4 and month<=6 then
set result:='第二季度';
when month>=7 and month<=9 then
set result:='第三季度';
when month>=10 and month<=12 then
set result:='第四季度';
else
set result:='非法参数';
end case;
select coucat('输入的月份:',month,',所属的季度为:=',result);
end;
call p6(momth:11);
while循环是有条件的循环控制语句。满足条件后,再执行循环体中的sql语句。
语法:
先判断条件,如果条件为true,则执行逻辑,否则,不执行逻辑。
while 条件 do
SQL逻辑
end while;
实例:
计算从1 累计加到n的值,n为传入的参数值。
//定义局部变量,记录累加后的值。
//每循环一次,就会对n进行减1,如果n减到0,则推出循环
create procedure p7(in n int)
begin
declare total int default 0;
while n>0 do
set total:=total+n;
set n:=n-1;
end while;
select total;
end;
call p7(n:10);
repeat:是有条件的循环控制语句,当满足条件的时候退出循环。
语法:
//先执行一次逻辑,然后判定逻辑是否满足,如果满足,则退出,如果不满足,则进行下次循环。
实例:计算从1 累计加到n的值,n为传入的参数值。
create procedure p8(in n int)
begin
declare total int default 0;
repeat
set total:=total+n;
set n:=n-1;
until n<=0;
end repeat;
select total;
end;
call p8(10);
loop 实现简单的循环,如果不在逻辑中增加退出循环的条件,可以用其他实现简单的死循环。 配合俩个语句使用:
leave:配合循环使用,退出循环。
iterate:必须用在循环中,作用是跳过当前循环剩下的语句,直接进入下一次循环。
语法:
[begin_lable: ] loop
SQL 逻辑....
END LOOP [end_label];
leave lable;退出指定标记的循环体。
iterate lable;直接进入下一次循环。
实例:
计算从1 累计加到n的值,n为传入的参数值。
create procedure p9(in n int)
begin
declare total int default 0;
sum:loop
if n<=0 then
end if;
set total:=total+n;
set n:=n-1;
end loop sum;
select total;
end;
call p9(10);
计算从 1 到n之间的偶数累加的数
create procedure p10(in n int)
begin
declare total int default 0;
sum:loop
if n<=0 then
end if;
if n%2=1 then
set n:=n-1;
end if
set total:=total+n;
set n:=n-1;
end loop sum;
select total;
end;
call p10(10);
游标是来存储查询结果集的数据类型,再存储过程和函数中可以使用游标对结果集进行循环的处理。 使用包括游标的声明,open,fetch,close
语法:
声明游标:declare 游标名称 cursor for 查询语句;
打开游标:open 游标名称;
获取游标记录: fetch 游标名称 into 变量
关闭游标:close 游标名称
案例: 根据传入的参数usge,来查询用户表tb_user中,所有的用户年龄小于灯鱼usge的用户姓名(name)和专业(profession),并将用户的姓名和专业插入到所创建的一张表中(id,name,profession)中。
思考逻辑实现:
1.声明游标,存储查询的结果集。
2.准备:创建表结构。
3.开启游标
4.获取游标中的记录
5.插入数据到新表中。
6.关闭游标
create procedure p11(in usge int)
begin
declare uname varchar(100);
declare upro varchar(100);
declare u_cursor cursor for select name,profession from tb_user where age<=usge;
create table if not exists tb_user_pro(
id int primary key auto_increment;
name varchar (100);
profession varchar(100);
)
open u_cursor;//打开
while true do
fetch u_cursor into uname,upro;
insert into tb_user_pro values(null,uname,upro);
end while;
ecd;
call p11(40);
注意:实际在敲完这部分代码时,会进行报错;要进行条件处理程序来处理。