Home > Database > Mysql Tutorial > body text

MySql中游标使用总是多循环一次的解决方法_MySQL

WBOY
Release: 2016-06-01 13:17:43
Original
1101 people have browsed it

CREATE DEFINER = 'root'@'%'PROCEDURE deyestest.procedure2()BEGIN   DECLARE v_id        INT;  DECLARE v_userName  VARCHAR(155);  DECLARE v_mobileNum VARCHAR(55);  DECLARE v_tmp       VARCHAR(1000);  DECLARE v_info      VARCHAR(2000);  DECLARE v_info2     VARCHAR(2000);  DECLARE v_int       INT;  DECLARE v_json      LONGTEXT;  DECLARE done        INT DEFAULT 0;  DECLARE myCursor CURSOR FOR  SELECT userId       , userName       , mobileNum  FROM    user_info  ORDER BY    userId  LIMIT    2, 2;  DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;  OPEN myCursor;  SET v_info = concat('{');   REPEAT    IF done <> 1 THEN  FETCH myCursor INTO v_id, v_userName, v_mobileNum;  SET v_tmp = concat('[', v_id, ',', v_userName, ',', v_mobileNum, ']', ',');  SET v_info = concat(v_info, v_tmp);  FETCH myCursor INTO v_id, v_userName, v_mobileNum;END IF;UNTIL doneEND REPEAT;  SET v_int = length(v_info);  SET v_info = left(v_info, v_int - 1);    SET v_info2 = concat(v_info, '}');  CLOSE myCursor;END
Copy after login

 

代码如上:

主要就是注意循环条件done的使用,当游标取到最后一个数据的下一个不存在的数据时,done会被值为1,那么就要在repeat中进行done的判断,当done不为1的时候,才执行循环。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!