标签:
测试表 level
代码如下:
create table test.level (name varchar(20));
初始化
代码如下:
drop procedure if exists useCursor //
CREATE PROCEDURE useCursor() BEGIN
declare tmpName varchar(20) default ‘‘ ; declare allName varchar(255) default ‘‘ ; declare cur1 CURSOR FOR SELECT name FROM test.level ;
并设置 循环使用 变量 tmpname 为 null 跳出循环。
代码如下:
declare CONTINUE HANDLER FOR SQLSTATE ‘02000‘ SET tmpname = null;
OPEN cur1;
FETCH cur1 INTO tmpName;
WHILE ( tmpname is not null) DO set tmpName = CONCAT(tmpName ,";") ; set allName = CONCAT(allName ,tmpName) ;
FETCH cur1 INTO tmpName;
END WHILE;
CLOSE cur1;
select allName ;
END;//
call useCursor()//
DELIMITER $$ DROP PROCEDURE IF EXITS cursor_example$$ CREATE PROCEDURE cursor_example() READS SQL DATA BEGIN DECLARE l_employee_id INT; DECLARE l_salary NUMERIC(8,2); DECLARE l_department_id INT; DECLARE done INT DEFAULT 0; DECLARE cur1 CURSOR FOR SELECT employee_id, salary, department_id FROM employees; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1; OPEN cur1; emp_loop: LOOP FETCH cur1 INTO l_employee_id, l_salary, l_department_id; IF done=1 THEN LEAVE emp_loop; END IF; END LOOP emp_loop; CLOSE cur1; END$$ DELIMITER ;
/*创建过程*/ DELIMITER // DROP PROCEDURE IF EXISTS test // CREATE PROCEDURE test() BEGIN DECLARE done INT DEFAULT 0; DECLARE a VARCHAR(200) DEFAULT ‘‘; DECLARE c VARCHAR(200) DEFAULT ‘‘; DECLARE mycursor CURSOR FOR SELECT fusername FROM uchome_friend; DECLARE CONTINUE HANDLER FOR NOT 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 // DROP PROCEDURE IF EXISTS test // CREATE PROCEDURE test() BEGIN DECLARE done INT DEFAULT 0; DECLARE a VARCHAR(200) DEFAULT ‘‘; DECLARE c VARCHAR(200) DEFAULT ‘‘; DECLARE mycursor CURSOR FOR SELECT fusername FROM uchome_friend; DECLARE CONTINUE HANDLER FOR NOT 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 ;
标签:
原文地址:http://www.cnblogs.com/lp-zy/p/4378525.html