DELIMITER $$ $$ CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clientRemoveWorker1`() BEGIN DECLARE vDone BOOL DEFAULT FALSE; DECLARE vClientFk INT; DECLARE rs CURSOR FOR SELECT c.clientFk FROM tmp.clientGetDebt c LEFT JOIN clientRisk r ON r.clientFk = c.clientFk GROUP BY c.clientFk HAVING SUM(IFNULL(r.amount,0)) = 0; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt SELECT cd.id as clientFk FROM bs.clientDied cd LEFT JOIN clientProtected cp ON cp.clientFk = cd.id JOIN client c ON c.id = cd.id JOIN province p ON p.id = c.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk JOIN country co ON co.id = p.countryFk WHERE cd.Aviso = 'TERCER AVISO' AND cp.clientFk IS NULL AND co.code NOT IN ('PT') AND a.name <> 'Canarias' AND c.salesPersonFk IS NOT NULL; OPEN rs; FETCH rs INTO vClientFk; WHILE NOT vDone DO CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); UPDATE vn.client SET salesPersonFk = NULL WHERE id = vClientFk; FETCH rs INTO vClientFk; END WHILE; CLOSE rs; DROP TEMPORARY TABLE tmp.clientGetDebt; END$$ DELIMITER ; CALL vn.clientRemoveWorker1(); DROP PROCEDURE vn.clientRemoveWorker1;