Bueno me respondo a mi mismo. Si alguien sabe como optimizar esta funcion, es bienvenida.
Saludos
Código Delphi
[-]
function fncSiguNume(suma : Integer = 0):Integer;
var
vValoReto : Integer;
begin
Query1.Close;
Query1.SQL.Clear;
Query1.SQL.Add('select count(codi) as Cuenta from tabla');
Query1.Open;
Query1.First;
vValoReto := Query1.FieldByName('Cuenta').AsInteger + suma;
Query1.Close;
Query1.SQL.Clear;
Query1.SQL.Add(format('select count(codi) as Cuenta from tabla where codi = %s',[IntToStr(vValoReto)]));
Query1.Open;
if Query1.FieldByName('Cuenta').AsInteger > 0 then
vValoReto := fncSiguNume(suma+1);
Result := vValoReto;
end;