存储过程 利用游标 解决复制业务

需求:
根据同一表的某条件更新字段

情况一: 以group by 作为条件的

select user a, (select count(*) as tj_num, s_id from user group by s_id) b set a.tuijian_num=b.tj_num where a.id=b.s_id; 

情况二: 不能以group by 作为条件的

#调用方法:call proc_update_team_info();
DELIMITER ;;
CREATE  PROCEDURE `proc_update_team_info`()
BEGIN	
	DECLARE done tinyint default 0;
	DECLARE uid int(11);
	DECLARE team_num int DEFAULT 0;
	DECLARE user_tree text DEFAULT '';
	DECLARE cs CURSOR FOR SELECT id FROM `user` order by id asc;
	DECLARE continue handler for sqlstate '02000' set done=1;
	open cs;
	while done<>1 do
    fetch cs into uid;
		select CONCAT(s_tree,id,',%') INTO user_tree  from `user` where id=uid;
		select user_tree;
		select if(count(*) is null,0,count(*)) into team_num  from `user` where s_tree like(user_tree);
		update `user` set team_num=team_num where id=uid;
	end while;
	close cs;	
END
;;
DELIMITER ;
posted @ 2018-11-20 10:51  geek程序员  阅读(195)  评论(0编辑  收藏  举报