使用Mysql 存储过程和游标进行同步数据

半世苍凉 提交于 2020-04-07 09:50:12

-- UpdateUserData是同步数据需要具体执行的步骤,AsyncUserData是控制UpdateUserData的条件。
DROP PROCEDURE IF EXISTS UpdateUserData;
DROP PROCEDURE IF EXISTS AsyncUserData; 
DELIMITER //
CREATE PROCEDURE `UpdateUserData`(IN id int(11))
BEGIN

 DECLARE classidstr VARCHAR(500);
 DECLARE gradeidstr VARCHAR(500);
 DECLARE stageidstr VARCHAR(500);
 DECLARE childidstr VARCHAR(500); 
 
 select CONCAT("[", GROUP_CONCAT( "\"",tb_child.class_id ,"\""), "]") into  classidstr from tb_child where patriarch_id=id;
 select CONCAT("[", GROUP_CONCAT(tb_child.grade_id), "]")  into  gradeidstr  from tb_child where patriarch_id=id;
 select CONCAT("[", GROUP_CONCAT(tb_child.stage_id), "]") into stageidstr from tb_child where patriarch_id=id;
 select CONCAT("[", GROUP_CONCAT(tb_child.child_id), "]") into  childidstr from tb_child where patriarch_id=id;
 IF childidstr is NULL
 THEN
 update tb_patriarch set class_ids='' , grade_ids ='' , stage_ids='' , child_ids='' where patriarch_id= id;
 ELSE
    update tb_patriarch set class_ids=classidstr , grade_ids =gradeidstr , stage_ids=stageidstr , child_ids=childidstr where patriarch_id= id;
 END IF;
END
//
DELIMITER ;
call UpdateUserData(4594);


DELIMITER //
CREATE PROCEDURE `AsyncUserData`()
BEGIN
 DECLARE id int(11);
 -- 定义遍历数据结束标志
 DECLARE done BOOLEAN DEFAULT 0;
 DECLARE curid CURSOR FOR select patriarch_id as id  from tb_patriarch where child_ids='[0]' ;
 --  当REPEAT由于没有更多的行供循环而不能继续时出现这个条件,将done设置为1,此时REPEAT终止
 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
  OPEN curid; 
    SET autocommit=0;
    read_loop:LOOP
  FETCH curid into id;
    IF done THEN
        LEAVE read_loop;
    END IF;
    call UpdateUserData(id);
  END LOOP;
  CLOSE curid;
END
//
call AsyncUserData(); 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!