WHILE ( tmpname isnotnull) DO set tmpName = CONCAT(tmpName ,";") ; set allName = CONCAT(allName ,tmpName) ;
-- 游标向下走一步 -- 代码如下:
FETCH cur1 INTO tmpName;
-- 结束循环体: -- 代码如下:
END WHILE;
-- 关闭游标 -- 代码如下: CLOSE cur1;
-- 选择数据 -- 代码如下: select allName ;
-- 结束存储过程 -- 代码如下: END;//
-- 调用存储过程: -- 代码如下:
call useCursor()//
-- loop循环游标: -- 代码如下: DELIMITER $$ DROPPROCEDURE IF EXITS cursor_example$$ CREATEPROCEDURE cursor_example() READSSQL DATA BEGIN DECLARE l_employee_id INT; DECLARE l_salary NUMERIC(8,2); DECLARE l_department_id INT; DECLARE done INTDEFAULT0; DECLARE cur1 CURSORFORSELECT employee_id, salary, department_id FROM employees; DECLARE CONTINUE HANDLER FORNOT FOUND SET done=1; OPEN cur1; emp_loop: LOOP FETCH cur1 INTO l_employee_id, l_salary, l_department_id; IF done=1THEN LEAVE emp_loop; END IF; END LOOP emp_loop; CLOSE cur1; END$$ DELIMITER ;
-- repeat循环游标: -- 代码如下: /*创建过程*/ DELIMITER // DROPPROCEDURE IF EXISTS test // CREATEPROCEDURE test() BEGIN DECLARE done INTDEFAULT0; DECLARE a VARCHAR(200) DEFAULT''; DECLARE c VARCHAR(200) DEFAULT''; DECLARE mycursor CURSORFORSELECT fusername FROM uchome_friend; DECLARE CONTINUE HANDLER FORNOT FOUND SET done=1; OPEN mycursor; REPEAT FETCH mycursor INTO a; IF NOT done THEN SET c=CONCAT(c,a);/*字符串相加*/ END IF; UNTIL done END REPEAT; CLOSE mycursor; SELECT c; END// DELIMITER ;
代码如下:
/*创建过程*/ DELIMITER // DROPPROCEDURE IF EXISTS test // CREATEPROCEDURE test() BEGIN DECLARE done INTDEFAULT0; DECLARE a VARCHAR(200) DEFAULT''; DECLARE c VARCHAR(200) DEFAULT''; DECLARE mycursor CURSORFORSELECT fusername FROM uchome_friend; DECLARE CONTINUE HANDLER FORNOT FOUND SET done=1; OPEN mycursor; REPEAT FETCH mycursor INTO a; IF NOT done THEN SET c=CONCAT(c,a);/*字符串相加*/ END IF; UNTIL done END REPEAT; CLOSE mycursor; SELECT c; END// DELIMITER ;