你了解mysql中的变量、流程控制与游标?下面本篇文章带大家了解一下mysql中的变量、流程控制与游标,希望对大家有所帮助。
1. 变量在mysql数据库的存储过程和函数中,可以使用变量来存储查询或计算的中间结果数据,或者输出最终的结果数据。
在 mysql 数据库中,变量分为系统变量以及用户自定义变量。【相关推荐:mysql视频教程】
1.1 系统变量1.1.1 系统变量分类变量由系统定义,不是用户定义,属于服务器层面。启动mysql服务,生成mysql服务实例期间,mysql将为mysql服务器内存中的系统变量赋值,这些系统变量定义了当前mysql服务实例的属性、特征。这些系统变量的值要么是编译mysql时参数的默认值,要么是配置文件(例如my.ini等)中的参数值。大家可以通过网址 https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html 查看mysql文档的系统变量。
系统变量分为全局系统变量(需要添加global 关键字)以及会话系统变量(需要添加 session 关键字),有时也把全局系统变量简称为全局变量,有时也把会话系统变量称为local变量。如果不写,默认会话级别。 静态变量(在 mysql 服务实例运行期间它们的值不能使用 set 动态修改)属于特殊的全局系统变量。
每一个mysql客户机成功连接mysql服务器后,都会产生与之对应的会话。会话期间,mysql服务实例会在mysql服务器内存中生成与该会话对应的会话系统变量,这些会话系统变量的初始值是全局系统变量值的复制。如下图:
全局系统变量针对于所有会话(连接)有效,但不能跨重启会话系统变量仅针对于当前会话(连接)有效。会话期间,当前会话对某个会话系统变量值的修改,不会影响其他会话同一个会话系统变量的值。会话1对某个全局系统变量值的修改会导致会话2中同一个全局系统变量值的修改。在mysql中有些系统变量只能是全局的,例如 max_connections 用于限制服务器的最大连接数;有些系统变量作用域既可以是全局又可以是会话,例如 character_set_client 用于设置客户端的字符集;有些系统变量的作用域只能是当前会话,例如 pseudo_thread_id 用于标记当前会话的 mysql 连接 id。
1.1.2 查看系统变量查看所有或部分系统变量#查看所有全局变量show global variables;#查看所有会话变量show session variables;或show variables;
#查看满足条件的部分系统变量。show global variables like '%标识符%';#查看满足条件的部分会话变量show session variables like '%标识符%';
举例:
show global variables like 'admin_%';
查看指定系统变量作为 mysql 编码规范,mysql 中的系统变量以两个“@”开头,其中“@@global”仅用于标记全局系统变量,“@@session”仅用于标记会话系统变量。“@@”首先标记会话系统变量,如果会话系统变量不存在,则标记全局系统变量。
#查看指定的系统变量的值select @@global.变量名;#查看指定的会话变量的值select @@session.变量名;#或者select @@变量名;
修改系统变量的值有些时候,数据库管理员需要修改系统变量的默认值,以便修改当前会话或者mysql服务实例的属性、特征。具体方法:
方式1:修改mysql配置文件,继而修改mysql系统变量的值(该方法需要重启mysql服务)
方式2:在mysql服务运行期间,使用“set”命令重新设置系统变量的值
#为某个系统变量赋值#方式1:set @@global.变量名=变量值;#方式2:set global 变量名=变量值;#为某个会话变量赋值#方式1:set @@session.变量名=变量值;#方式2:set session 变量名=变量值;
举例:
select @@global.autocommit;set global autocommit=0;
select @@session.tx_isolation;set @@session.tx_isolation='read-uncommitted';
set global max_connections = 1000;select @@global.max_connections;
1.2 用户变量1.2.1 用户变量分类用户变量是用户自己定义的,作为 mysql 编码规范,mysql 中的用户变量以一个“@”开头。根据作用范围不同,又分为会话用户变量和局部变量。
会话用户变量:作用域和会话变量一样,只对当前连接会话有效。
局部变量:只在 begin 和 end 语句块中有效。局部变量只能在存储过程和函数中使用。
1.2.2 会话用户变量变量的定义#方式1:“=”或“:=”set @用户变量 = 值;set @用户变量 := 值;#方式2:“:=” 或 into关键字select @用户变量 := 表达式 [from 等子句];select 表达式 into @用户变量 [from 等子句];
查看用户变量的值 (查看、比较、运算等)select @用户变量
举例set @a = 1;select @a;
select @num := count(*) from employees;select @num;
select avg(salary) into @avgsalary from employees;select @avgsalary;
select @big; #查看某个未声明的变量时,将得到null值
1.2.3 局部变量定义:可以使用declare语句定义一个局部变量
作用域:仅仅在定义它的 begin ... end 中有效
位置:只能放在 begin ... end 中,而且只能放在第一句
begin #声明局部变量 declare 变量名1 变量数据类型 [default 变量默认值]; declare 变量名2,变量名3,... 变量数据类型 [default 变量默认值]; #为局部变量赋值 set 变量名1 = 值; select 值 into 变量名2 [from 子句]; #查看局部变量的值 select 变量1,变量2,变量3;end
1.定义变量
declare 变量名 类型 [default 值]; # 如果没有default子句,初始值为null
举例:
declare myparam int default 100;
2.变量赋值
方式1:一般用于赋简单的值
set 变量名=值;set 变量名:=值;
方式2:一般用于赋表中的字段值
select 字段名或表达式 into 变量名 from 表;
3.使用变量(查看、比较、运算等)
select 局部变量名;
举例1:声明局部变量,并分别赋值为employees表中employee_id为102的last_name和salary
delimiter //create procedure set_value()begin declare emp_name varchar(25); declare sal double(10,2); select last_name,salary into emp_name,sal from employees where employee_id = 102; select emp_name,sal;end //delimiter ;
举例2:声明两个变量,求和并打印 (分别使用会话用户变量、局部变量的方式实现)
#方式1:使用用户变量set @m=1;set @n=1;set @sum=@m+@n;select @sum;
#方式2:使用局部变量delimiter //create procedure add_value()begin #局部变量 declare m int default 1; declare n int default 3; declare sum int; set sum = m+n; select sum;end //delimiter ;
举例3:创建存储过程“different_salary”查询某员工和他领导的薪资差距,并用in参数emp_id接收员工id,用out参数dif_salary输出薪资差距结果。
#声明delimiter //create procedure different_salary(in emp_id int,out dif_salary double)begin #声明局部变量 declare emp_sal,mgr_sal double default 0.0; declare mgr_id int; select salary into emp_sal from employees where employee_id = emp_id; select manager_id into mgr_id from employees where employee_id = emp_id; select salary into mgr_sal from employees where employee_id = mgr_id; set dif_salary = mgr_sal - emp_sal;end //delimiter ;#调用set @emp_id = 102;call different_salary(@emp_id,@diff_sal);#查看select @diff_sal;
1.2.4 对比会话用户变量与局部变量 作用域 定义位置 语法会话用户变量 当前会话 会话的任何地方 加@符号,不用指定类型局部变量 定义它的begin end中 begin end的第一句话 一般不用加@,需要指定类型
2. 定义条件与处理程序定义条件是事先定义程序执行过程中可能遇到的问题,处理程序定义了在遇到问题时应当采取的处理方式,并且保证存储过程或函数在遇到警告或错误时能继续执行。这样可以增强存储程序处理问题的能力,避免程序异常停止运行。
说明:定义条件和处理程序在存储过程、存储函数中都是支持的。
2.1 案例分析案例分析: 创建一个名称为“updatedatanocondition”的存储过程。代码如下:
delimiter //create procedure updatedatanocondition() begin set @x = 1; update employees set email = null where last_name = 'abel'; set @x = 2; update employees set email = 'aabbel' where last_name = 'abel'; set @x = 3; end //delimiter ;
调用存储过程:
mysql> call updatedatanocondition();error 1048 (23000): column 'email' cannot be nullmysql> select @x;+------+| @x |+------+| 1 |+------+1 row in set (0.00 sec)
可以看到,此时@x变量的值为1。结合创建存储过程的sql语句代码可以得出:在存储过程中未定义条件和处理程序,且当存储过程中执行的sql语句报错时,mysql数据库会抛出错误,并退出当前sql逻辑,不再向下继续执行。
2.2 定义条件定义条件就是给mysql中的错误码命名,这有助于存储的程序代码更清晰。它将一个错误名字和指定的错误条件关联起来。这个名字可以随后被用在定义处理程序的declare handler语句中。
定义条件使用declare语句,语法格式如下:
declare 错误名称 condition for 错误码(或错误条件)
错误码的说明:
mysql_error_code和sqlstate_value都可以表示mysql的错误。mysql_error_code是数值类型错误代码。sqlstate_value是长度为5的字符串类型错误代码。例如,在error 1418 (hy000)中,1418是mysql_error_code,'hy000'是sqlstate_value。例如,在error 1142(42000)中,1142是mysql_error_code,'42000'是sqlstate_value。举例1: 定义“field_not_be_null”错误名与mysql中违反非空约束的错误类型是“error 1048 (23000)”对应。
#使用mysql_error_codedeclare field_not_be_null condition for 1048;#使用sqlstate_valuedeclare field_not_be_null condition for sqlstate '23000';
举例2: 定义"error 1148(42000)"错误,名称为command_not_allowed。
#使用mysql_error_codedeclare command_not_allowed condition for 1148;#使用sqlstate_valuedeclare command_not_allowed condition for sqlstate '42000';
2.3 定义处理程序可以为sql执行过程中发生的某种类型的错误定义特殊的处理程序。定义处理程序时,使用declare语句的语法如下:
declare 处理方式 handler for 错误类型 处理语句
处理方式:处理方式有3个取值:continue、exit、undo。continue:表示遇到错误不处理,继续执行。exit:表示遇到错误马上退出。undo:表示遇到错误后撤回之前的操作。mysql中暂时不支持这样的操作。错误类型(即条件)可以有如下取值:sqlstate '字符串错误码':表示长度为5的sqlstate_value类型的错误代码;mysql_error_code:匹配数值类型错误代码;错误名称:表示declare ... condition定义的错误条件名称。sqlwarning:匹配所有以01开头的sqlstate错误代码;not found:匹配所有以02开头的sqlstate错误代码;sqlexception:匹配所有没有被sqlwarning或not found捕获的sqlstate错误代码;处理语句:如果出现上述条件之一,则采用对应的处理方式,并执行指定的处理语句。语句可以是像“set 变量 = 值”这样的简单语句,也可以是使用begin ... end编写的复合语句。定义处理程序的几种方式,代码如下:
#方法1:捕获sqlstate_valuedeclare continue handler for sqlstate '42s02' set @info = 'no_such_table';#方法2:捕获mysql_error_valuedeclare continue handler for 1146 set @info = 'no_such_table';#方法3:先定义条件,再调用declare no_such_table condition for 1146;declare continue handler for no_such_table set @info = 'no_such_table';#方法4:使用sqlwarningdeclare exit handler for sqlwarning set @info = 'error';#方法5:使用not founddeclare exit handler for not found set @info = 'no_such_table';#方法6:使用sqlexceptiondeclare exit handler for sqlexception set @info = 'error';
2.4 案例解决在存储过程中,定义处理程序,捕获sqlstate_value值,当遇到mysql_error_code值为1048时,执行continue操作,并且将@proc_value的值设置为-1。
delimiter //create procedure updatedatanocondition() begin #定义处理程序 declare continue handler for 1048 set @proc_value = -1; set @x = 1; update employees set email = null where last_name = 'abel'; set @x = 2; update employees set email = 'aabbel' where last_name = 'abel'; set @x = 3; end //delimiter ;
调用过程:
mysql> call updatedatawithcondition();query ok, 0 rows affected (0.01 sec)mysql> select @x,@proc_value;+------+-------------+| @x | @proc_value |+------+-------------+| 3 | -1 |+------+-------------+1 row in set (0.00 sec)
举例:
创建一个名称为“insertdatawithcondition”的存储过程,代码如下。
在存储过程中,定义处理程序,捕获sqlstate_value值,当遇到sqlstate_value值为23000时,执行exit操作,并且将@proc_value的值设置为-1。
#准备工作create table departmentsasselect * from atguigudb.`departments`;alter table departmentsadd constraint uk_dept_name unique(department_id);
delimiter //create procedure insertdatawithcondition() begin declare duplicate_entry condition for sqlstate '23000' ; declare exit handler for duplicate_entry set @proc_value = -1; set @x = 1; insert into departments(department_name) values('测试'); set @x = 2; insert into departments(department_name) values('测试'); set @x = 3; end //delimiter ;
调用存储过程:
mysql> call insertdatawithcondition();query ok, 0 rows affected (0.01 sec)mysql> select @x,@proc_value;+------+-------------+| @x | @proc_value |+------+-------------+| 2 | -1 |+------+-------------+1 row in set (0.00 sec)
3. 流程控制解决复杂问题不可能通过一个 sql 语句完成,我们需要执行多个 sql 操作。流程控制语句的作用就是控制存储过程中 sql 语句的执行顺序,是我们完成复杂操作必不可少的一部分。只要是执行的程序,流程就分为三大类:
顺序结构:程序从上往下依次执行分支结构:程序按条件进行选择执行,从两条或多条路径中选择一条执行循环结构:程序满足一定条件下,重复执行一组语句针对于mysql 的流程控制语句主要有 3 类。注意:只能用于存储程序。
条件判断语句:if 语句和 case 语句循环语句:loop、while 和 repeat 语句跳转语句:iterate 和 leave 语句3.1 分支结构之 ifif 语句的语法结构是:if 表达式1 then 操作1[elseif 表达式2 then 操作2]……[else 操作n]end if
根据表达式的结果为true或false执行相应的语句。这里“[]”中的内容是可选的。
特点:① 不同的表达式对应不同的操作 ② 使用在begin end中
举例1:
if val is null then select 'val is null';else select 'val is not null';end if;
举例2: 声明存储过程“update_salary_by_eid1”,定义in参数emp_id,输入员工编号。判断该员工薪资如果低于8000元并且入职时间超过5年,就涨薪500元;否则就不变。
delimiter //create procedure update_salary_by_eid1(in emp_id int)begin declare emp_salary double; declare hire_year double; select salary into emp_salary from employees where employee_id = emp_id; select datediff(curdate(),hire_date)/365 into hire_year from employees where employee_id = emp_id; if emp_salary < 8000 and hire_year > 5 then update employees set salary = salary + 500 where employee_id = emp_id; end if;end //delimiter ;
举例3: 声明存储过程“update_salary_by_eid2”,定义in参数emp_id,输入员工编号。判断该员工薪资如果低于9000元并且入职时间超过5年,就涨薪500元;否则就涨薪100元。
delimiter //create procedure update_salary_by_eid2(in emp_id int)begin declare emp_salary double; declare hire_year double; select salary into emp_salary from employees where employee_id = emp_id; select datediff(curdate(),hire_date)/365 into hire_year from employees where employee_id = emp_id; if emp_salary < 8000 and hire_year > 5 then update employees set salary = salary + 500 where employee_id = emp_id; else update employees set salary = salary + 100 where employee_id = emp_id; end if;end //delimiter ;
举例4: 声明存储过程“update_salary_by_eid3”,定义in参数emp_id,输入员工编号。判断该员工薪资如果低于9000元,就更新薪资为9000元;薪资如果大于等于9000元且低于10000的,但是奖金比例为null的,就更新奖金比例为0.01;其他的涨薪100元。
delimiter //create procedure update_salary_by_eid3(in emp_id int)begin declare emp_salary double; declare bonus decimal(3,2); select salary into emp_salary from employees where employee_id = emp_id; select commission_pct into bonus from employees where employee_id = emp_id; if emp_salary < 9000 then update employees set salary = 9000 where employee_id = emp_id; elseif emp_salary < 10000 and bonus is null then update employees set commission_pct = 0.01 where employee_id = emp_id; else update employees set salary = salary + 100 where employee_id = emp_id; end if;end //delimiter ;
3.2 分支结构之 casecase 语句的语法结构1:
#情况一:类似于switchcase 表达式when 值1 then 结果1或语句1(如果是语句,需要加分号) when 值2 then 结果2或语句2(如果是语句,需要加分号)...else 结果n或语句n(如果是语句,需要加分号)end [case](如果是放在begin end中需要加上case,如果放在select后面不需要)
case 语句的语法结构2:
#情况二:类似于多重ifcase when 条件1 then 结果1或语句1(如果是语句,需要加分号) when 条件2 then 结果2或语句2(如果是语句,需要加分号)...else 结果n或语句n(如果是语句,需要加分号)end [case](如果是放在begin end中需要加上case,如果放在select后面不需要)
举例1:使用case流程控制语句的第1种格式,判断val值等于1、等于2,或者两者都不等。
case val when 1 then select 'val is 1'; when 2 then select 'val is 2'; else select 'val is not 1 or 2';end case;
举例2:使用case流程控制语句的第2种格式,判断val是否为空、小于0、大于0或者等于0。
case when val is null then select 'val is null'; when val < 0 then select 'val is less than 0'; when val > 0 then select 'val is greater than 0'; else select 'val is 0';end case;
举例3: 声明存储过程“update_salary_by_eid4”,定义in参数emp_id,输入员工编号。判断该员工薪资如果低于9000元,就更新薪资为9000元;薪资大于等于9000元且低于10000的,但是奖金比例为null的,就更新奖金比例为0.01;其他的涨薪100元。delimiter //create procedure update_salary_by_eid4(in emp_id int)begin declare emp_sal double; declare bonus decimal(3,2); select salary into emp_sal from employees where employee_id = emp_id; select commission_pct into bonus from employees where employee_id = emp_id; case when emp_sal<9000 then update employees set salary=9000 where employee_id = emp_id; when emp_sal<10000 and bonus is null then update employees set commission_pct=0.01 where employee_id = emp_id; else update employees set salary=salary+100 where employee_id = emp_id; end case;end //delimiter ;
举例4:声明存储过程update_salary_by_eid5,定义in参数emp_id,输入员工编号。判断该员工的入职年限,如果是0年,薪资涨50;如果是1年,薪资涨100;如果是2年,薪资涨200;如果是3年,薪资涨300;如果是4年,薪资涨400;其他的涨薪500。delimiter //create procedure update_salary_by_eid5(in emp_id int)begin declare emp_sal double; declare hire_year double; select salary into emp_sal from employees where employee_id = emp_id; select round(datediff(curdate(),hire_date)/365) into hire_year from employees where employee_id = emp_id; case hire_year when 0 then update employees set salary=salary+50 where employee_id = emp_id; when 1 then update employees set salary=salary+100 where employee_id = emp_id; when 2 then update employees set salary=salary+200 where employee_id = emp_id; when 3 then update employees set salary=salary+300 where employee_id = emp_id; when 4 then update employees set salary=salary+400 where employee_id = emp_id; else update employees set salary=salary+500 where employee_id = emp_id; end case;end //delimiter ;
3.3 循环结构之looploop循环语句用来重复执行某些语句。loop内的语句一直重复执行直到循环被退出(使用leave子句),跳出循环过程。
loop语句的基本格式如下:
[loop_label:] loop 循环执行的语句end loop [loop_label]
其中,loop_label表示loop语句的标注名称,该参数可以省略。
举例1:
使用loop语句进行循环操作,id值小于10时将重复执行循环过程。
declare id int default 0;add_loop:loop set id = id +1; if id >= 10 then leave add_loop; end if;end loop add_loop;
举例2: 当市场环境变好时,公司为了奖励大家,决定给大家涨工资。声明存储过程“update_salary_loop()”,声明out参数num,输出循环次数。存储过程中实现循环给大家涨薪,薪资涨为原来的1.1倍。直到全公司的平均薪资达到12000结束。并统计循环次数。
delimiter //create procedure update_salary_loop(out num int)begin declare avg_salary double; declare loop_count int default 0; select avg(salary) into avg_salary from employees; label_loop:loop if avg_salary >= 12000 then leave label_loop; end if; update employees set salary = salary * 1.1; set loop_count = loop_count + 1; select avg(salary) into avg_salary from employees; end loop label_loop; set num = loop_count;end //delimiter ;
3.4 循环结构之whilewhile语句创建一个带条件判断的循环过程。while在执行语句执行时,先对指定的表达式进行判断,如果为真,就执行循环内的语句,否则退出循环。while语句的基本格式如下:
[while_label:] while 循环条件 do 循环体end while [while_label];
while_label为while语句的标注名称;如果循环条件结果为真,while语句内的语句或语句群被执行,直至循环条件为假,退出循环。
举例1:
while语句示例,i值小于10时,将重复执行循环过程,代码如下:
delimiter //create procedure test_while()begin declare i int default 0; while i < 10 do set i = i + 1; end while; select i;end //delimiter ;#调用call test_while();
举例2: 市场环境不好时,公司为了渡过难关,决定暂时降低大家的薪资。声明存储过程“update_salary_while()”,声明out参数num,输出循环次数。存储过程中实现循环给大家降薪,薪资降为原来的90%。直到全公司的平均薪资达到5000结束。并统计循环次数。
delimiter //create procedure update_salary_while(out num int)begin declare avg_sal double ; declare while_count int default 0; select avg(salary) into avg_sal from employees; while avg_sal > 5000 do update employees set salary = salary * 0.9; set while_count = while_count + 1; select avg(salary) into avg_sal from employees; end while; set num = while_count;end //delimiter ;
3.5 循环结构之repeatrepeat语句创建一个带条件判断的循环过程。与while循环不同的是,repeat 循环首先会执行一次循环,然后在 until 中进行表达式的判断,如果满足条件就退出,即 end repeat;如果条件不满足,则会就继续执行循环,直到满足退出条件为止。
repeat语句的基本格式如下:
[repeat_label:] repeat循环体的语句until 结束循环的条件表达式end repeat [repeat_label]
repeat_label为repeat语句的标注名称,该参数可以省略;repeat语句内的语句或语句群被重复,直至expr_condition为真。
举例1:
delimiter //create procedure test_repeat()begin declare i int default 0; repeat set i = i + 1; until i >= 10 end repeat; select i;end //delimiter ;
举例2: 当市场环境变好时,公司为了奖励大家,决定给大家涨工资。声明存储过程“update_salary_repeat()”,声明out参数num,输出循环次数。存储过程中实现循环给大家涨薪,薪资涨为原来的1.15倍。直到全公司的平均薪资达到13000结束。并统计循环次数。
delimiter //create procedure update_salary_repeat(out num int)begin declare avg_sal double ; declare repeat_count int default 0; select avg(salary) into avg_sal from employees; repeat update employees set salary = salary * 1.15; set repeat_count = repeat_count + 1; select avg(salary) into avg_sal from employees; until avg_sal >= 13000 end repeat; set num = repeat_count; end //delimiter ;
对比三种循环结构:
1、这三种循环都可以省略名称,但如果循环中添加了循环控制语句(leave或iterate)则必须添加名称。2、loop:一般用于实现简单的"死"循环while:先判断后执行repeat:先执行后判断,无条件至少执行一次
3.6 跳转语句之leave语句leave语句:可以用在循环语句内,或者以 begin 和 end 包裹起来的程序体内,表示跳出循环或者跳出程序体的操作。如果你有面向过程的编程语言的使用经验,你可以把 leave 理解为 break。
基本格式如下:
leave 标记名
其中,label参数表示循环的标志。leave和begin ... end或循环一起被使用。
**举例1:**创建存储过程 “leave_begin()”,声明int类型的in参数num。给begin...end加标记名,并在begin...end中使用if语句判断num参数的值。
如果num<=0,则使用leave语句退出begin...end;如果num=1,则查询“employees”表的平均薪资;如果num=2,则查询“employees”表的最低薪资;如果num>2,则查询“employees”表的最高薪资。if语句结束后查询“employees”表的总人数。
delimiter //create procedure leave_begin(in num int) begin_label: begin if num<=0 then leave begin_label; elseif num=1 then select avg(salary) from employees; elseif num=2 then select min(salary) from employees; else select max(salary) from employees; end if; select count(*) from employees; end //delimiter ;
举例2:
当市场环境不好时,公司为了渡过难关,决定暂时降低大家的薪资。声明存储过程“leave_while()”,声明out参数num,输出循环次数,存储过程中使用while循环给大家降低薪资为原来薪资的90%,直到全公司的平均薪资小于等于10000,并统计循环次数。
delimiter //create procedure leave_while(out num int)begin # declare avg_sal double;#记录平均工资 declare while_count int default 0; #记录循环次数 select avg(salary) into avg_sal from employees; #① 初始化条件 while_label:while true do #② 循环条件 #③ 循环体 if avg_sal <= 10000 then leave while_label; end if; update employees set salary = salary * 0.9; set while_count = while_count + 1; #④ 迭代条件 select avg(salary) into avg_sal from employees; end while; #赋值 set num = while_count;end //delimiter ;
3.7 跳转语句之iterate语句iterate语句:只能用在循环语句(loop、repeat和while语句)内,表示重新开始循环,将执行顺序转到语句段开头处。如果你有面向过程的编程语言的使用经验,你可以把 iterate 理解为 continue,意思为“再次循环”。
语句基本格式如下:
iterate label
label参数表示循环的标志。iterate语句必须跟在循环标志前面。
举例: 定义局部变量num,初始值为0。循环结构中执行num + 1操作。
如果num < 10,则继续执行循环;如果num > 15,则退出循环结构;delimiter //create procedure test_iterate()begin declare num int default 0; my_loop:loop set num = num + 1; if num < 10 then iterate my_loop; elseif num > 15 then leave my_loop; end if; select '尚硅谷:让天下没有难学的技术'; end loop my_loop;end //delimiter ;
4. 游标4.1 什么是游标(或光标)虽然我们也可以通过筛选条件 where 和 having,或者是限定返回记录的关键字 limit 返回一条记录,但是,却无法在结果集中像指针一样,向前定位一条记录、向后定位一条记录,或者是随意定位到某一条记录,并对记录的数据进行处理。
这个时候,就可以用到游标。游标,提供了一种灵活的操作方式,让我们能够对结果集中的每一条记录进行定位,并对指向的记录中的数据进行操作的数据结构。游标让 sql 这种面向集合的语言有了面向过程开发的能力。
在 sql 中,游标是一种临时的数据库对象,可以指向存储在数据库表中的数据行指针。这里游标充当了指针的作用,我们可以通过操作游标来对数据行进行操作。
mysql中游标可以在存储过程和函数中使用。
比如,我们查询了 employees 数据表中工资高于15000的员工都有哪些:
select employee_id,last_name,salary from employeeswhere salary > 15000;
这里我们就可以通过游标来操作数据行,如图所示此时游标所在的行是“108”的记录,我们也可以在结果集上滚动游标,指向结果集中的任意一行。
4.2 使用游标步骤游标必须在声明处理程序之前被声明,并且变量和条件还必须在声明游标或处理程序之前被声明。
如果我们想要使用游标,一般需要经历四个步骤。不同的 dbms 中,使用游标的语法可能略有不同。
第一步,声明游标
在mysql中,使用declare关键字来声明游标,其语法的基本形式如下:
declare cursor_name cursor for select_statement;
这个语法适用于 mysql,sql server,db2 和 mariadb。如果是用 oracle 或者 postgresql,需要写成:
declare cursor_name cursor is select_statement;
要使用 select 语句来获取数据结果集,而此时还没有开始遍历数据,这里 select_statement 代表的是 select 语句,返回一个用于创建游标的结果集。
比如:
declare cur_emp cursor for select employee_id,salary from employees;
declare cursor_fruit cursor for select f_name, f_price from fruits ;
第二步,打开游标
打开游标的语法如下:
open cursor_name
当我们定义好游标之后,如果想要使用游标,必须先打开游标。打开游标的时候 select 语句的查询结果集就会送到游标工作区,为后面游标的逐条读取结果集中的记录做准备。
open cur_emp ;
第三步,使用游标(从游标中取得数据)
语法如下:
fetch cursor_name into var_name [, var_name] ...
这句的作用是使用 cursor_name 这个游标来读取当前行,并且将数据保存到 var_name 这个变量中,游标指针指到下一行。如果游标读取的数据行有多个列名,则在 into 关键字后面赋值给多个变量名即可。
注意:var_name必须在声明游标之前就定义好。
fetch cur_emp into emp_id, emp_sal ;
注意:游标的查询结果集中的字段数,必须跟 into 后面的变量数一致,否则,在存储过程执行的时候,mysql 会提示错误。
第四步,关闭游标
close cursor_name
有 open 就会有 close,也就是打开和关闭游标。当我们使用完游标后需要关闭掉该游标。因为游标会占用系统资源,如果不及时关闭,游标会一直保持到存储过程结束,影响系统运行的效率。而关闭游标的操作,会释放游标占用的系统资源。
关闭游标之后,我们就不能再检索查询结果中的数据行,如果需要检索只能再次打开游标。
close cur_emp;
4.3 举例创建存储过程“get_count_by_limit_total_salary()”,声明in参数 limit_total_salary,double类型;声明out参数total_count,int类型。函数的功能可以实现累加薪资最高的几个员工的薪资值,直到薪资总和达到limit_total_salary参数的值,返回累加的人数给total_count。
delimiter //create procedure get_count_by_limit_total_salary(in limit_total_salary double,out total_count int)begin declare sum_salary double default 0; #记录累加的总工资 declare cursor_salary double default 0; #记录某一个工资值 declare emp_count int default 0; #记录循环个数 #定义游标 declare emp_cursor cursor for select salary from employees order by salary desc; #打开游标 open emp_cursor; repeat #使用游标(从游标中获取数据) fetch emp_cursor into cursor_salary; set sum_salary = sum_salary + cursor_salary; set emp_count = emp_count + 1; until sum_salary >= limit_total_salary end repeat; set total_count = emp_count; #关闭游标 close emp_cursor; end //delimiter ;
4.5 小结游标是 mysql 的一个重要的功能,为逐条读取结果集中的数据,提供了完美的解决方案。跟在应用层面实现相同的功能相比,游标可以在存储程序中使用,效率高,程序也更加简洁。
但同时也会带来一些性能问题,比如在使用游标的过程中,会对数据行进行加锁,这样在业务并发量大的时候,不仅会影响业务之间的效率,还会消耗系统资源,造成内存不足,这是因为游标是在内存中进行的处理。
建议:养成用完之后就关闭的习惯,这样才能提高系统的整体效率。
补充:mysql 8.0的新特性—全局变量的持久化在mysql数据库中,全局变量可以通过set global语句来设置。例如,设置服务器语句超时的限制,可以通过设置系统变量max_execution_time来实现:
set global max_execution_time=2000;
使用set global语句设置的变量值只会临时生效。数据库重启后,服务器又会从mysql配置文件中读取变量的默认值。mysql 8.0版本新增了set persist命令。例如,设置服务器的最大连接数为1000:
set persist global max_connections = 1000;
mysql会将该命令的配置保存到数据目录下的mysqld-auto.cnf文件中,下次启动时会读取该文件,用其中的配置来覆盖默认的配置文件。
举例:
查看全局变量max_connections的值,结果如下:
mysql> show variables like '%max_connections%';+------------------------+-------+| variable_name | value |+------------------------+-------+| max_connections | 151 || mysqlx_max_connections | 100 |+------------------------+-------+2 rows in set, 1 warning (0.00 sec)
设置全局变量max_connections的值:
mysql> set persist max_connections=1000;query ok, 0 rows affected (0.00 sec)
重启mysql服务器,再次查询max_connections的值:
mysql> show variables like '%max_connections%';+------------------------+-------+| variable_name | value |+------------------------+-------+| max_connections | 1000 || mysqlx_max_connections | 100 |+------------------------+-------+2 rows in set, 1 warning (0.00 sec)
更多编程相关知识,请访问:编程入门!!
以上就是你了解mysql中的变量、流程控制与游标?的详细内容。