DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`Vehiculos_consumo_calculateLiters100km`()
BEGIN
	DECLARE vConsumptionVehicleId INT;
	DECLARE vDone BOOL;
	DECLARE vOldKm INT;
	DECLARE vOldLiters INT;
	DECLARE vNewKm INT;
	DECLARE vVehicleId INT;

	DECLARE cur CURSOR FOR
		SELECT Vehiculos_consumo_id, Id_Vehiculo, km FROM vn2008.Vehiculos_consumo;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	OPEN cur;

	l: LOOP
		SET vDone = FALSE;
		FETCH cur INTO vConsumptionVehicleId, vVehicleId, vNewKm;

		IF vDone THEN
			LEAVE l;
		END IF;
	
		SELECT km, litros INTO vOldKm, vOldLiters 
			FROM Vehiculos_consumo
			WHERE Id_Vehiculo = vVehicleId
				AND Vehiculos_consumo_id < vConsumptionVehicleId
			ORDER BY Vehiculos_consumo_id DESC
			LIMIT 1;
		
		UPDATE Vehiculos_consumo 
			SET liters100km = vOldLiters/((vNewKm-vOldKm)*0.01)
			WHERE Vehiculos_consumo_id = vConsumptionVehicleId;
		
	END LOOP;

	CLOSE cur;
	
END$$
DELIMITER ;
