USE ejemplo;
/* usar frontera = 50 */

DROP PROCEDURE IF EXISTS reparte;
DELIMITER $
CREATE PROCEDURE reparte(frontera INT)
BEGIN
	DECLARE suma INT DEFAULT 0;
	DECLARE matricula_actual INT;
	DECLARE creditos_actual INT;
	DECLARE fin BOOL DEFAULT FALSE;
	DECLARE cur CURSOR FOR SELECT matricula, creditos FROM alumnos;
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET fin = TRUE;
	
	OPEN cur;
	
leer:
	LOOP
		FETCH cur INTO matricula_actual, creditos_actual;
		
		IF fin THEN
			LEAVE leer;
		END IF;
		
		IF creditos_actual > frontera THEN
			SET suma = suma + (creditos_actual - frontera);
			UPDATE alumnos SET creditos = frontera WHERE matricula = matricula_actual;
		END IF;
	END LOOP;
	
	CLOSE cur;
	
guardar:
	WHILE suma > 0 DO
		SELECT matricula, creditos INTO matricula_actual, creditos_actual FROM alumnos ORDER BY creditos ASC LIMIT 1;

		IF creditos_actual = frontera THEN
			LEAVE guardar;
		END IF;
		
		SET suma = suma - 1;
		UPDATE alumnos SET creditos = creditos + 1 WHERE matricula = matricula_actual;
	END WHILE;
END $
DELIMITER ;