The solution to using cursors in MySql is always multiple cycles.

Source: Internet
Author: User

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

 

The Code is as follows:

Pay attention to the use of the cyclic condition done. When the cursor obtains the next nonexistent data of the last data, the done will be set to 1, so the done should be judged in the repeat, when done is not 1, a loop is executed.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.