DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`client_getRisk`(
	vDate DATE
)
BEGIN
/**
 * Retorna el riesgo de los clientes activos.
 *
 * @param vDate Fecha a calcular
 */
	CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt
		(PRIMARY KEY (clientFk))
		ENGINE = MEMORY
		SELECT id clientFk
			FROM client
			WHERE isActive;

	CALL client_getDebt(vDate);

	SELECT c.socialName,
			r.clientFk,
			c.credit,
			CAST(r.risk AS DECIMAL (10,2)) risk,
			CAST(c.credit - r.risk AS DECIMAL (10,2)) difference,
			co.name country
		FROM client c
			JOIN tmp.risk r ON r.clientFk = c.id
			JOIN country co ON co.id = c.countryFk
		GROUP BY c.id;

	DROP TEMPORARY TABLE
		tmp.risk,
		tmp.clientGetDebt;
END$$
DELIMITER ;
