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

53 lines
1.5 KiB
SQL

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`client_unassignSalesPerson`()
BEGIN
/**
* Elimina la asignación de salesPersonFk de la ficha del clientes
* que no han realizado una compra en los últimos 3 meses y reparte
* su greuge entre el resto de clientes
*/
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vClientFk INT;
DECLARE vCursor CURSOR FOR
SELECT c.clientFk
FROM tClientList c
LEFT JOIN clientRisk r ON r.clientFk = c.clientFk
GROUP BY c.clientFk
HAVING NOT SUM(IFNULL(r.amount, 0));
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
CREATE OR REPLACE TEMPORARY TABLE tClientList
SELECT c.id clientFk
FROM bs.clientDied cd
JOIN client c ON c.id = cd.clientFk
LEFT JOIN clientProtected cp ON cp.clientFk = c.id
LEFT JOIN salesPersonProtected sp ON sp.salesPersonFk = c.salesPersonFk
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
JOIN bs.clientDiedPeriod cdp ON cdp.countryFk = co.id
WHERE cd.warning = 'third'
AND cp.clientFk IS NULL
AND sp.salesPersonFk IS NULL
AND a.name <> 'Canarias'
AND c.salesPersonFk IS NOT NULL;
OPEN vCursor;
l: LOOP
SET vDone = FALSE;
FETCH vCursor INTO vClientFk;
IF vDone THEN
LEAVE l;
END IF;
CALL clientGreugeSpray(vClientFk, TRUE, '', TRUE);
UPDATE client
SET salesPersonFk = NULL
WHERE id = vClientFk;
END LOOP;
CLOSE vCursor;
DROP TEMPORARY TABLE tClientList;
END$$
DELIMITER ;