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.