DROP FUNCTION IF EXISTS softsat_locacao_boleto_sequencia;
delimiter //
CREATE FUNCTION `softsat_locacao_boleto_sequencia`()
RETURNS INT
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
    DECLARE seq INT DEFAULT 1;
    DECLARE free INT DEFAULT 0;

    SELECT VALUE INTO seq FROM hwapx_setting WHERE id = 'softsat.locacao.boleto.sequencia';

    WHILE(free = 0)DO
        IF(EXISTS(SELECT 1 FROM softsat_locacao_boleto WHERE sequencia = seq AND (cancelado = 0 OR (cancelado = 1 AND remessa_criacao IS NOT NULL))))THEN
            SET seq = seq + 1;
        ELSE
            SET free = 1;
        END IF;
    END WHILE;

    RETURN seq;
END//

SELECT softsat_locacao_boleto_sequencia()

/*SELECT 1 FROM softsat_locacao_boleto
WHERE sequencia = 1 AND (cancelado = 0 OR (cancelado = 1 AND remessa_criacao IS NOT NULL))*/