DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`riskAllClients`(maxRiskDate DATE)
BEGIN
	
	DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt;
	CREATE TEMPORARY TABLE tmp.clientGetDebt
	(PRIMARY KEY (clientFk))
		ENGINE = MEMORY
		SELECT id clientFk, null grade FROM client;

	CALL client_getDebt (maxRiskDate);

	SELECT 
			c.RazonSocial,
			c.Id_Cliente,
			c.Credito,
			CAST(r.risk as DECIMAL (10,2)) risk,
			CAST(c.Credito - r.risk as DECIMAL (10,2)) Diferencia,
			c.Id_Pais
		FROM
			vn2008.Clientes c
				JOIN tmp.risk r ON r.clientFk = c.Id_Cliente
				JOIN tmp.clientGetDebt ci ON c.Id_Cliente = ci.clientFk
			GROUP BY c.Id_cliente;

	DROP TEMPORARY TABLE IF EXISTS tmp.risk;
	DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt;
END$$
DELIMITER ;
