儲存過程 利用遊標 解決複製業務
阿新 • • 發佈:2018-11-20
需求:
根據同一表的某條件更新欄位
情況一: 以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 ;