Mysql中的存储程序——游标

在《Mysql是怎样使用的》这本书中,游标所占的篇幅并不长,只是简单写了一下使用游标获取记录的方法。这块内容并不常用,所以有这种待遇也挺正常的,在这里我也简单提一下

在学习游标之前,我们对多个变量赋值是这样的

select c1,c2,c3 from t where id=n INTO n1,n2,n3;

这里有三列数据,但只有一行。如果有多行记录,则不方便赋值了。为了方便以行的形式读取记录,思想上类似于其他语言中的指针。使用游标应该:创建——>打开——>操作——>关闭。

 

创建游标

注意创建游标需要在声明的局部变量之后

declare 游标名 cursor for 查询语句

 

使用游标

游标一般用在存储函数或存储过程中。它的存在就是标记当前访问的某一条目录。获取到记录之后,再移动到下一条记录,因此需要循环语句去执行读取记录的操作:

fetch 游标名 into 变量1,变量2,变量n……

而在循环时,一旦fetch 语句循环结束找不到记录了,就会返回一个No DATA ERROR,此时在存储函数中,可以用提前声明错误的方式来防止其抛出错误,并且以此为条件结束循环:

declare countinue hadler for not found 处理语句   //只要定义了这个,fetch语句在找不到记录时就会执行这里填写的语句,这里甚至可以写begin……end包裹的多条语句

 

案例(游标获取用户记录):

mysql> create procedure ocursor_demo()
    -> begin
    -> declare id_value int;
    -> declare uname_value varchar(20);   //设置需要查询的列,对应的输出参数
    -> declare done int default 0;        //设置跳出循环条件的值
    -> declare users_cursor cursor for select id, username from users;  //创建游标,语句为查询需要的列
    -> declare continue handler for not found set done = 1;    //捕获报错为循环结束条件,当读取完所有记录后就会报错,这条语句会捕获报错并使跳出循环条件为真
    -> open users_cursor; //开启游标
    -> flag:loop  
    -> fetch users_cursor into id_value, uname_value;  //循环读取读取每一行的记录
    -> if done = 1 then  //当done值为1时跳出循环
    -> leave flag;
    -> end if;
    -> select id_value, uname_value, done;  //每次循环都会输出一个结果集
    -> end loop flag;
    -> close users_cursor;  //游标使用结束后关闭
    -> end #
Query OK, 0 rows affected (0.00 sec)
mysql> call ocursor_demo#   //调用存储过程,打印每行结果
+----------+-------------+------+
| id_value | uname_value | done |
+----------+-------------+------+
|        1 | root        |    0 |
+----------+-------------+------+
1 row in set (0.00 sec)

+----------+-------------+------+
| id_value | uname_value | done |
+----------+-------------+------+
|        2 | 789         |    0 |
+----------+-------------+------+
1 row in set (0.00 sec)

+----------+-------------+------+
| id_value | uname_value | done |
+----------+-------------+------+
|        3 | linkdo      |    0 |
+----------+-------------+------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

 

posted @ 2021-12-25 14:03  我永远喜欢石原里美  阅读(255)  评论(0)    收藏  举报