0613游标及其应用 MySQL 下面的定义符合一个游标声明 declare xs cur 1 cursor for select学号,姓名,性别,出生日期,总学分 ft rom Xs where 专业名三'计算机 MySQL数据库应用》http:/mysql.xg.hactcm.edu.cn 第6页
《MySQL数据库应用》 http://mysql.xg.hactcm.edu.cn/ 第 6 页 6.1.3游标及其应用 下面的定义符合一个游标声明: declare xs_cur1 cursor for select 学号,姓名,性别,出生日期,总学分 from xs where 专业名 = '计算机';
0613游标及其应用 MySQL (2)打开游标 声明游标后,要使用游标从中提取数据,就必须先打开游标。 使用0PEN语句打开游标,其格式为: 0PEN游标名 例如:打开游标ⅹscur1。 open Xs cur1 MySQL数据库应用》http:/mysql.xg.hactcm.edu.cn 第7页
《MySQL数据库应用》 http://mysql.xg.hactcm.edu.cn/ 第 7 页 6.1.3游标及其应用 (2)打开游标 声明游标后,要使用游标从中提取数据,就必须先打开游标。 使用OPEN语句打开游标,其格式为: OPEN 游标名 例如:打开游标xs_cur1。 open xs_cur1
0613游标及其应用 MySQL (3)读取数据 游标打开后,就可以使用FET啡H…INT0语句从中读取数据。 语法格式: FETCH游标名INTo变量名 将查询到的数据存储在变量中,因此需要读取刚才打开过的游标 fetch xs cur1 into xh, xm, xb, csrg, zxf 的数交颁等声游时。匚LcU了可牛列的数日 MySQL数据库应用》http:/mysql.xg.hactcm.edu.cn 第8页
《MySQL数据库应用》 http://mysql.xg.hactcm.edu.cn/ 第 8 页 6.1.3游标及其应用 (3)读取数据 游标打开后,就可以使用FETCH…INTO语句从中读取数据。 语法格式: FETCH 游标名 INTO 变量名 ... 说明: - FETCH ...INTO语句与SELECT...INTO语句具有相同的意义; - FETCH语句是将游标指向的一行数据赋给一些变量, FETCH子句中变量 的数目必须等于声明游标时SELECT子句中列的数目。 将查询到的数据存储在变量中,因此需要读取刚才打开过的游标: fetch xs_cur1 into xh,xm,xb,csrq,zxf;
0613游标及其应用 MySQL (4)关闭游标 游标使用完以后,要及时关闭。关闭游标使用CL0SE语句。 语法格式为: CLOSE游标名 例如:关闭游标 xs cur1 ClOSE XS cur 1 MySQL数据库应用》http:/mysql.xg.hactcm.edu.cn 第9页
《MySQL数据库应用》 http://mysql.xg.hactcm.edu.cn/ 第 9 页 6.1.3游标及其应用 (4)关闭游标 游标使用完以后,要及时关闭。关闭游标使用CLOSE语句。 语法格式为: CLOSE 游标名 例如:关闭游标xs_cur1。 CLOSE xs_cur1
0613游标及其应用 MySQL 【例69】创建一个存储过程,计算xs表中行的数目。 del imiter $$ create procedure compute out number integer) egIn declare xh char(6) declare found boo lean defau ltt number xs:游标名 declare number xs-cursor fo select学号 from xs; declare cont inue handler for not found set found=false set number =0 open number xs fetch number xs into xh: whi le found do set number=number +1 fetch number xs into xh end while close number xs: ends de l imiter cal I compute (enum); select @num; MySQL数据库应用》ht: mysql xg. hactcm edu.cn 第10页
《MySQL数据库应用》 http://mysql.xg.hactcm.edu.cn/ 第 10 页 6.1.3游标及其应用 【例6.9】创建一个存储过程,计算xs表中行的数目。 delimiter $$ create procedure compute(out number integer) begin declare xh char(6); declare found boolean default true; declare number_xs cursor for select 学号 from xs; declare continue handler for not found set found=false; set number=0; open number_xs; fetch number_xs into xh; while found do set number=number+1; fetch number_xs into xh; end while; close number_xs; end$$ delimiter ; call compute(@num); select @num; number_xs :游标名