public static int GetHastaNumeroProximo(int idTalonario) { int result; using (var sqlCmd = new SqlCommand()) { // select (max)numero from comprobantes where IdTalonario= Comprobantes.IdTalonario and anulado=0 var sql = string.Format("select max({0}) from {1} where {2} = @valor", ComprobantesBOFieldNames.HastaNumero.ToString, this.TableNameAndSchema, ComprobantesBOFieldNames.IdTalonario.ToString); sqlCmd.CommandTimeout = 0; // Added this to avoid taking to much time, also make sure your tables are properly indexed for the SQL condition sqlCmd.CommandText = sql; sqlCmd.Parameters.Add("@valor", SqlDbType.Int).Value = idTalonario; //Also noticed that this parameter should be Integer and not String as you had it originaly. var res = this.ExecuteScalar(sqlCmd); result = (res == null) || res == DBNull.Value ? 1 : ((int)res) + 1; } // end using return result; }