DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`Facturas_Saltos`(IN datSTART DATE , IN datEND DATE)
BEGIN


DECLARE strSER1 VARCHAR(2);
DECLARE strSER2 VARCHAR(2);
DECLARE intEMP1 INT;
DECLARE intEMP2 INT;
DECLARE v_done BOOLEAN DEFAULT FALSE;
DECLARE strFAC1 VARCHAR(11);
DECLARE strFAC2 VARCHAR(11);


DECLARE rs CURSOR FOR
	SELECT Id_Factura, empresa_id, Serie 
    FROM Facturas 
    WHERE Fecha BETWEEN datSTART AND datEND
    ORDER BY empresa_id, Serie, Id_Factura;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_done = TRUE;

OPEN rs;

DROP TEMPORARY TABLE IF EXISTS Facturas_Saltarinas;

CREATE TEMPORARY TABLE Facturas_Saltarinas
(Factura_Inicial VARCHAR(11),
 Factura_Final VARCHAR(11),
 Empresa VARCHAR(3),
 Serie VARCHAR(1));

FETCH rs INTO strFAC1, intEMP1, strSER1;

IF NOT v_done THEN

	FETCH rs INTO strFAC2, intEMP2, strSER2;
    
END IF;

WHILE NOT v_done DO

	IF strSER1 = strSER2 AND intEMP1 = intEMP2 AND right(strFAC2,5) - right(strFAC1,5) > 1 then
    
		INSERT INTO Facturas_Saltarinas(Factura_Inicial, Factura_Final, Empresa, Serie)
        SELECT strFAC1, strFAC2, abbreviation, strSER1
        FROM empresa
        WHERE id = intEMP1;
    
    END IF;

	SET strFAC1 = strFAC2;
	SET intEMP1 = intEMP2;
	SET STRSER1 = strSER2;

	FETCH rs INTO strFAC2, intEMP2, strSER2;

END WHILE;

SELECT * FROM Facturas_Saltarinas;

CLOSE rs;

END$$
DELIMITER ;
