1、变量
变量又可分为系统变量、自定义变量和局部变量
1.1 系统变量
顾名思义就是系统提供的变量,不能创建、只能使用,系统变量又包含全局变量(global)和会话变量(session)
1.1.1 查看所有系统变量
show [global|session] variables; --查看所有变量show [global|session] variables like '%%';-- 模糊查询系统变量
1.1.2 系统变量的设置
set [global|session] 系统变量名:=值;set @@[global|session] 系统变量名:=值;--有@@代表是系统变量
1.2 自定义变量
根据需求定义的变量,在使用时用@标识
1.2.1 赋值
set @自定义变量名:=值;select 字段名 into @变量名 from 表名;
1.3 局部变量
根据需求的业务要求出现在存储过程begin end之间,在使用前需要先申明
1.3.1 申明
declare 变量名 类型 default 值;--申明一个变量并给一个默认值
1.3.2 赋值
set 变量名:=值;select 字段名 into 变量名 from 表名;
2、if语句
语法
if 条件1 then语句1elseif 条件2 then语句2elseif 条件3 then语句3...else语句end if;
实例:
用存储过程和if语句实现以下需求
1.已知成绩sc
sc>=85 优秀
sc>=60 及格
sc<60 不及格
delimiter $$ --创建一个结束标识,语句到$$结束create procedure pro002()begindeclare score int default 55;declare result varchar(10) '';if score>=85 && score<=100 thenset score:='优秀';elseif score>=60 thenset score:='及格';elseset score:='不及格';end if;end$$call pro002();select @result;
运行结果为不及格,如果想要其他结果,需要改变存储过程名,改变变量的值
这样灵活性很低,因此引出存储过程的参数,就能很轻易解决这个问题
存储过程参数类型
in --作为输入参数out --作为输出参数inout --输入/输出参数,类型只能是同一种
delimiter $$ --创建一个结束标识,语句到$$结束create procedure pro003(in score int,out result varchar(10))-- 形式参数begin-- declare score int default 55;-- declare result varchar(10) '';if score>=85 && score<=100 thenset score:='优秀';elseif score>=60 thenset score:='及格';elseset score:='不及格';end if;end$$call pro002(55,@result);-- 实际参数select @result;
同上需求,只需要将参数in和out使用,就能在不更改存储过程的同时达到想要的效果
只需要在调用时输入相关的值,就能得到相应的结果。
3、while循环
语法:
while 表达式 do循环体end while;
实例:用存储过程和while循环实现1到100的累加
delimiter $$create procedure pro003(in N int,out sum int)beginset sum:=0;while N>0 dosum=sum+N;N=N-1;end while;end$$call pro003(100,@sum);select @sum;
以上就是这期的全部内容了
每天学习一点,每天进步一点