分支函数之if结构:if(表达式1,表达式2,表达式3)函数;if 条件 then 语句;elseif then
"if(表达式1,表达式2,表达式3)":可以用在任何地方
如果表达式1成立,则返回表达式2;
如果表达式1不成立,则返回表示式3;
"在函数中输入一个年龄,给年龄分组":
delimiter
create function mmp2(age int) returns varchar(22)
begin
if age>=60 and age<=110 then return '老人';
elseif age between 30 and 60 then return '中年人'
else return '小人';
end if;
end $
select mmp2(23)$
分支函数之case结构:语句后面加 ; ,
"begin end之外的时"
case age
when 11 then "返回"
when 22 then "返回"
else "返回"
end
case
when age>11 then "返回"
when age>22 then "返回"
else "返回"
end
"在存储过程中输入一个年龄,给年龄分组":
delimiter $
create procedure mmp(in age int)
begin
case
when age>=60 then select '老人';
when age>=30 then select '中年人';
else select '小人';
end case;
end $
call mmp(50)$
循环:while,loop,repeat
"简单的while循环":
"进行多次添加数据"
delimiter $
create procedure mmp(in number int)
begin
declare led int default 1;
while led<=number do
insert into 表(id,name) values(concat('rod',led),'0000');
set led=led+1;
end while;
end $
call mmp(100)$
"添加标签":使用leave,iterate的时候需要用到标签
delimiter $
create procedure mmp(in number int)
begin
declare led int default 1;
a:while led<=number do
insert into 表(id,name) values(concat('rod',led),'0000');
set led=led+1;
end while a;
end $
循环中的break,continue:SQL中iterate类似continue,leave类似break
"使用leave停止while循环"
delimiter $
create procedure mmp1(in number int)
begin
declare led int default 1;
a:while led<=number do
if led>=20
then leave a;
end if;
insert into 表(id,name) values(concat(('rod'),led),'0000');
set led=led+1;
end while a;
end $
call mmp(100)$
"iterate:"
delimiter $
create procedure mmp2(number int)
begin
declare led int default 0;
a:while led<=number do
set led=led+1;
if mod(led,2)==0 then iterate a;
end if;
insert into 表(id,name) values(concat(('rod'),led),'0000');
end while a;
end $
call mmp2(100)$
"loop无线循环"
a:loop
循环体
end loop a;
"先执行在判断"
a:repeat
循环体;
until 结束条件
end repeat a;