mysql 多重游标嵌套
1、DECLARE CONTINUE HANDLER FOR NOT FOUND
在mysql的存储过程中经常会看到这句话:DECLARE CONTINUE HANDLER FOR NOT FOUND
它的含义是:若没有数据返回,程序继续,并将变量IS_FOUND设为0 ,这种情况是出现在select XX into XXX from tablename的时候发生的。
2、查询每个年级下都有哪些班级,一张年级表(org_grade)一张班级表(org_class)
2.1 建表
CREATE TABLE erp.org_grade (
grade_Id int(11) NOT NULL AUTO_INCREMENT,
grade_name varchar(255) DEFAULT NULL,
PRIMARY KEY (grade_Id)
)
ENGINE = MYISAM
AUTO_INCREMENT = 2
AVG_ROW_LENGTH = 20
CHARACTER SET utf8
COLLATE utf8_general_ci;
grade_Id int(11) NOT NULL AUTO_INCREMENT,
grade_name varchar(255) DEFAULT NULL,
PRIMARY KEY (grade_Id)
)
ENGINE = MYISAM
AUTO_INCREMENT = 2
AVG_ROW_LENGTH = 20
CHARACTER SET utf8
COLLATE utf8_general_ci;
CREATE TABLE erp.org_class (
class_Id int(11) NOT NULL AUTO_INCREMENT,
class_name varchar(255) DEFAULT NULL,
grade_id int(11) DEFAULT NULL,
PRIMARY KEY (class_Id)
)
ENGINE = MYISAM
AUTO_INCREMENT = 3
AVG_ROW_LENGTH = 20
CHARACTER SET utf8
COLLATE utf8_general_ci;
class_Id int(11) NOT NULL AUTO_INCREMENT,
class_name varchar(255) DEFAULT NULL,
grade_id int(11) DEFAULT NULL,
PRIMARY KEY (class_Id)
)
ENGINE = MYISAM
AUTO_INCREMENT = 3
AVG_ROW_LENGTH = 20
CHARACTER SET utf8
COLLATE utf8_general_ci;
2.2过程示例
CREATE PROCEDURE good_nested_cursors1( )
READS SQL DATA
BEGIN
DECLARE l_grade_id INT;
DECLARE l_class_id INT;
DECLARE l_class_cnt INT DEFAULT 0 ;
DECLARE l_done INT DEFAULT 0;
DECLARE grade_csr cursor FOR SELECT grade_id FROM org_grade;
DECLARE class_csr cursor FOR SELECT class_id FROM org_class WHERE grade_id=l_grade_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET l_done=1;
OPEN grade_csr;
grade_loop: LOOP -- Loop through org_grade
FETCH grade_csr into l_grade_id;
select concat('年级:', l_grade_id);
IF l_done=1 THEN
LEAVE grade_loop;
END IF;
OPEN class_csr;
SET l_class_cnt=0;
class_loop: LOOP -- Loop through class in grade.
FETCH class_csr INTO l_class_id;
IF l_done=1 THEN
LEAVE class_loop;
END IF;
SET l_class_cnt=l_class_cnt+1;
select concat(' 班级:', l_class_id);
END LOOP class_loop;
CLOSE class_csr;
SET l_done=0;
END LOOP grade_loop;
CLOSE grade_csr;
END;
READS SQL DATA
BEGIN
DECLARE l_grade_id INT;
DECLARE l_class_id INT;
DECLARE l_class_cnt INT DEFAULT 0 ;
DECLARE l_done INT DEFAULT 0;
DECLARE grade_csr cursor FOR SELECT grade_id FROM org_grade;
DECLARE class_csr cursor FOR SELECT class_id FROM org_class WHERE grade_id=l_grade_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET l_done=1;
OPEN grade_csr;
grade_loop: LOOP -- Loop through org_grade
FETCH grade_csr into l_grade_id;
select concat('年级:', l_grade_id);
IF l_done=1 THEN
LEAVE grade_loop;
END IF;
OPEN class_csr;
SET l_class_cnt=0;
class_loop: LOOP -- Loop through class in grade.
FETCH class_csr INTO l_class_id;
IF l_done=1 THEN
LEAVE class_loop;
END IF;
SET l_class_cnt=l_class_cnt+1;
select concat(' 班级:', l_class_id);
END LOOP class_loop;
CLOSE class_csr;
SET l_done=0;
END LOOP grade_loop;
CLOSE grade_csr;
END;