DELIMITER $$
DROP FUNCTION IF EXISTS pagado_convenio_fecha;
CREATE FUNCTION pagado_convenio_fecha
(convenio$ INT, fecha$ DATETIME)
RETURNS DECIMAL(8,2)
BEGIN
	DECLARE resultset DECIMAL(8,2) DEFAULT(0.00);
	DECLARE valor_convenio DECIMAL(8,2);
	SET valor_convenio := (SELECT valor FROM convenios WHERE id = convenio$);
	IF EXISTS (SELECT id FROM recibos WHERE convenio = convenio$ AND registro < fecha$) THEN
		SET resultset := (valor_convenio -(SELECT SUM(m.pago) FROM recibos AS r INNER JOIN mantto AS m ON r.id = m.recibo WHERE r.convenio = convenio$ AND r.registro < fecha$));
	ELSE
		SET resultset = valor_convenio;
	END IF;
	RETURN resultset;
END
$$

DELIMITER $$
DROP FUNCTION IF EXISTS pagado_convenio;
CREATE FUNCTION pagado_convenio
(convenio$ INT)
RETURNS DECIMAL(8,2)
BEGIN
    DECLARE resultset DECIMAL(8,2) DEFAULT(0.00);
    IF EXISTS (SELECT id FROM recibos WHERE convenio = convenio$) THEN
        SET resultset := (SELECT SUM(m.pago) FROM recibos AS r INNER JOIN mantto AS m ON m.recibo = r.id WHERE r.convenio = convenio$);
    END IF;
    RETURN resultset;
END
$$
