salix/db/routines/vn/procedures/clientRemoveWorker.sql

41 lines
1.2 KiB
SQL

DELIMITER $$
CREATE OR REPLACE DEFINER=`vn-admin`@`localhost` PROCEDURE `vn`.`clientRemoveWorker`()
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;
DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt;
CREATE TEMPORARY TABLE tmp.clientGetDebt
SELECT cd.clientFk
FROM bs.clientDied cd
LEFT JOIN clientProtected cp ON cp.clientFk = cd.clientFk
JOIN client c ON c.id = cd.clientFk
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.warning = 'third'
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 ;