时间:2021-07-01 10:21:17 帮助过:13人阅读
#函数
/*
存储过程:可以有0个或多个返回,适合批量插入、批量更新
函数:有且仅有一个返回,适合处理数据后返回一个结果
*/
#一、创建语法
/*
create function 函数名(参数列表) returns 返回类型
begin
函数体
end
参数列表:
参数名 参数类型
*/
use myemployees;
set global log_bin_trust_function_creators=TRUE;
#案例1:返回公司的员工个数
delimiter &
create function myf1() returns int
begin
declare c int default 0; #定义变量
select count(*) into c #赋值
from employees;
return c;
end &
#调用函数用select
select myf1()&
#案例2:根据员工名,返回工资
create function myf2(empName varchar(20)) returns double
begin
set @sal=0;
select salary into @sal
from employees
where last_name=empName;
return @sal;
end &
select myf2(‘Kochhar‘)&
#查看函数
show create function myf2&
#删除函数
# drop function myf3;
#流程控制结构
/*
顺序结构
分支结构
循环结构
*/
#一、分支
/*
1.if函数
select if(表达式1, 表达式2, 表达式3)
如果表达式1成立,返回表达式2,否则返回表达式3
2.case结构
实现等值或区间判断
case 变量|表达式|字段
when 要判断的值 then 返回的值或语句1;
when 要判断的值 then 返回的值或语句2;
...
else 返回的值n;
end case;
*/
#案例:创建存储过程,跟据传入的成绩来显示等级
create procedure test_case(
in score int
)
begin
case
when score >=90 and score <= 100 then select ‘A‘;
when score >=80 then select ‘B‘;
when score >=60 then select ‘C‘;
else select ‘D‘;
end case;
end&
call test_case(95)&
#if结构,实现多重分支
/*
只能应用在begin end中
if 条件1 then 语句1;
elseif 条件2 then 语句2;
...
else 语句n;
end if;
*/
#案例:创建存储过程,跟据传入的成绩返回级别
create function test_if(score int) returns char
begin
if score >= 90 and score <= 100 then return ‘A‘;
elseif score >= 80 then return ‘B‘;
elseif score >=60 then return ‘C‘;
else return ‘D‘;
end if;
end&
select test_if(75)&
#循环结构
/*
while, loop, repeat
循环控制:
iterate 类似于continue
leave 类似于break
1、while
【标签:】while 循环条件 do
循环体;
end while 【标签】;
2、loop
【标签:】loop
循环体;
end loop 【标签】;
可以用来模拟简单的死循环
3、repeat
【标签:】repeat
循环体;
until 结束条件
end repeat 【标签】;
*/
#案例:批量插入,根据次数插入到admin表中多条记录
use girls&
drop procedure pro_while1&
create procedure pro_while1(
in insertcount int
)
begin
declare i int default 1;
while i <= insertcount do
insert into admin(username, password) values(concat(‘rois‘,i), ‘666‘);
set i = i+1;
end while;
end&
call pro_while1(5)&
select * from admin&
#案例:批量插入,根据次数插入到admin表中多条记录,如果次数>20则停止
create procedure pro_while2(
in insertcount int
)
begin
declare i int default 1;
a:while i <= insertcount do
insert into admin(username, password) values(concat(‘xiaohua‘,i), ‘777‘);
if i >= 20 then leave a;
end if;
set i = i+1;
end while a;
end&
call pro_while2(22)&
select * from admin&
mysql-18-function
标签:lse begin when 类型 数列 记录 rop def call