2017年9月25日月曜日

MYSQL カーソルのネスト

DELIMITER //
CREATE PROCEDURE test1()
BEGIN
  DECLARE not_found INT DEFAULT 0;
  DECLARE v_deptno INT;
  DECLARE v_dname VARCHAR(14);
  DECLARE cur1 CURSOR FOR SELECT deptno FROM emp ORDER BY empno;
  DECLARE cur2 CURSOR FOR SELECT dname FROM dept WHERE deptno = v_deptno;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET not_found = 1;
 
  OPEN cur1;
  loop1: LOOP
    FETCH cur1 INTO v_deptno;
    IF not_found THEN
      CLOSE cur1;
      LEAVE loop1;
    END IF;
   
    OPEN cur2;
    loop2: LOOP
      FETCH cur2 INTO v_dname;
      IF not_found THEN
        SET not_found = 0; ← フラグを戻す
        CLOSE cur2;
        LEAVE loop2;
      END IF;
      INSERT INTO work (dname) VALUES (v_dname);
    END LOOP;
  END LOOP;
END
//
DELIMITER ;

0 件のコメント:

コメントを投稿