DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`clientNewBorn_recalc`() BLOCK1: BEGIN DECLARE vClientFk INT; DECLARE vShipped DATE; DECLARE vPreviousShipped DATE; DECLARE vDone boolean; DECLARE cur cursor for SELECT clientFk, firstShipped FROM bs.clientNewBorn; DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE; SET vDone := FALSE; DELETE FROM bs.clientNewBorn WHERE isModified = FALSE; INSERT INTO clientNewBorn(clientFk, firstShipped, lastShipped) SELECT c.id, MAX(t.shipped), MAX(t.shipped) FROM vn.client c JOIN vn.ticket t on t.clientFk = c.id LEFT JOIN clientNewBorn cb on cb.clientFk = c.id WHERE t.shipped BETWEEN TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) AND util.VN_CURDATE() AND cb.isModified is null GROUP BY c.id; OPEN cur; LOOP1: LOOP SET vDone := FALSE; FETCH cur INTO vClientFk, vShipped; IF vDone THEN CLOSE cur; LEAVE LOOP1; END IF; BLOCK2: BEGIN DECLARE vCurrentShipped DATE; DECLARE vDone2 boolean; DECLARE cur2 CURSOR FOR SELECT shipped FROM vn.ticket WHERE clientFk = vClientFk AND shipped <= util.VN_CURDATE() ORDER BY shipped DESC; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone2 = TRUE; SET vDone2 := FALSE; OPEN cur2; SET vPreviousShipped := vShipped; LOOP2: LOOP SET vDone2 := FALSE; FETCH cur2 INTO vCurrentShipped; IF DATEDIFF(vPreviousShipped,vCurrentShipped) > 365 THEN UPDATE bs.clientNewBorn SET firstShipped = vPreviousShipped WHERE clientFk= vClientFk; CLOSE cur2; LEAVE LOOP2; END IF; SET vPreviousShipped := vCurrentShipped; IF vDone2 THEN UPDATE bs.clientNewBorn SET firstShipped = vCurrentShipped WHERE clientFk= vClientFk; CLOSE cur2; LEAVE LOOP2; END IF; END LOOP LOOP2; END BLOCK2; END LOOP LOOP1; UPDATE bs.clientNewBorn cnb LEFT JOIN (SELECT DISTINCT t.clientFk FROM vn.ticket t JOIN vn.productionConfig pc WHERE t.shipped BETWEEN util.VN_CURDATE() + INTERVAL -(`notBuyingMonths`) MONTH AND util.VN_CURDATE() + INTERVAL -(`pc`.`rookieDays`) DAY) notRookie ON notRookie.clientFk = cnb.clientFk SET cnb.isRookie = ISNULL(notRookie.clientFk); END BLOCK1$$ DELIMITER ;