2012-01-08 9 views
16

stavo attraversando la documentazione SOQL, ma non riusciva a trovare query per recuperare tutti i dati del campo di un'entità dicono, account, comeSalesforce SOQL: query per recuperare tutti i campi per l'entità

select * from Account [ SQL syntax ] 

C'è una sintassi come quella sopra in SOQL per recuperare tutti i dati dell'account, o l'unico modo è quello di elencare tutti i campi (anche se ci sono molti campi da interrogare)

risposta

16

Devi specificare i campi, se vuoi creare qualcosa di dinamico, la chiamata describeSObject restituisce i metadati relativi a tutti i campi per un oggetto, in modo da poterne creare la query.

+2

grazie per la tua risposta. Ti dispiacerebbe condividere un esempio, per costruire la query da describeSObject. – Sukhhhh

24

Creare una mappa del genere:

Map<String, Schema.SObjectField> fldObjMap = schema.SObjectType.Account.fields.getMap(); 
List<Schema.SObjectField> fldObjMapValues = fldObjMap.values(); 

Poi si può scorrere fldObjMapValues ​​per creare una query string SOQL:

String theQuery = 'SELECT '; 
for(Schema.SObjectField s : fldObjMapValues) 
{ 
    String theLabel = s.getDescribe().getLabel(); // Perhaps store this in another map 
    String theName = s.getDescribe().getName(); 
    String theType = s.getDescribe().getType(); // Perhaps store this in another map 

    // Continue building your dynamic query string 
    theQuery += theName + ','; 
} 

// Trim last comma 
theQuery = theQuery.subString(0, theQuery.length() - 1); 

// Finalize query string 
theQuery += ' FROM Account WHERE ... AND ... LIMIT ...'; 

// Make your dynamic call 
Account[] accounts = Database.query(theQuery); 

superfell è corretta, non c'è modo di fare direttamente un SELECT *. Tuttavia, questa piccola ricetta del codice funzionerà (beh, non l'ho ancora testata, ma penso che sia ok). Comprensibilmente Force.com vuole un'architettura multi-tenant in cui le risorse vengano fornite come esplicitamente necessarie, non facilmente facendo SELECT * quando in genere solo un sottoinsieme di campi è effettivamente necessario.

+0

Grazie Adam. Come d'accordo con superfell, accetterà la sua risposta :-) – Sukhhhh

+0

Ovviamente Sukhhhh :) – Adam

6

Uso l'Explorer di Force.com e all'interno del filtro dello schema è possibile fare clic sulla casella accanto a TableName e selezionerà tutti i campi e inserirli nella finestra della query. Lo uso come collegamento per digitare tutto - Basta copiare e incollare dalla finestra della query. Spero che questo ti aiuti.

3

Nel caso qualcuno era alla ricerca di un approccio C#, sono stato in grado di utilizzare la riflessione e venire con la seguente:

public IEnumerable<String> GetColumnsFor<T>() 
{ 
    return typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance) 
     .Where(x => !Attribute.IsDefined(x, typeof(System.Xml.Serialization.XmlIgnoreAttribute))) // Exclude the ignored properties 
     .Where(x => x.DeclaringType != typeof(sObject)) // & Exclude inherited sObject propert(y/ies) 
     .Where(x => x.PropertyType.Namespace != typeof(Account).Namespace) // & Exclude properties storing references to other objects 
     .Select(x => x.Name); 
} 

E sembra funzionare per gli oggetti che ho provato (e le partite le colonne generato dal test API). Da lì, si tratta di creare la query:

/* assume: this.server = new sForceService(); */ 

public IEnumerable<T> QueryAll<T>(params String[] columns) 
    where T : sObject 
{ 
    String soql = String.Format("SELECT {0} FROM {1}", 
     String.Join(", ", GetColumnsFor<T>()), 
     typeof(T).Name 
    ); 
    this.service.QueryOptionsValue = new QueryOptions 
    { 
     batchsize = 250, 
     batchSizeSpecified = true 
    }; 
    ICollection<T> results = new HashSet<T>(); 
    try 
    { 
     Boolean done = false; 
     QueryResult queryResult = this.service.queryAll(soql); 
     while (!finished) 
     { 
      sObject[] records = queryResult.records; 
      foreach (sObject record in records) 
      { 
       T entity = entity as T; 
       if (entity != null) 
       { 
        results.Add(entity); 
       } 
      } 
      done &= queryResult.done; 
      if (!done) 
      { 
       queryResult = this.service.queryMode(queryResult.queryLocator); 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     throw; // your exception handling 
    } 
    return results; 
} 
+0

Bravo Brad, ha funzionato! – Shazoo

1

per me è stata la prima volta con Salesforce oggi e sono arrivato fino a questo in Java:

/** 
* @param o any class that extends {@link SObject}, f.ex. Opportunity.class 
* @return a list of all the objects of this type 
*/ 
@SuppressWarnings("unchecked") 
public <O extends SObject> List<O> getAll(Class<O> o) throws Exception { 
    // get the objectName; for example "Opportunity" 
    String objectName= o.getSimpleName(); 

    // this will give us all the possible fields of this type of object 
    DescribeSObjectResult describeSObject = connection.describeSObject(objectName); 

    // making the query 
    String query = "SELECT "; 
    for (Field field : describeSObject.getFields()) { // add all the fields in the SELECT 
     query += field.getName() + ','; 
    } 
    // trim last comma 
    query = query.substring(0, query.length() - 1); 

    query += " FROM " + objectName; 

    SObject[] records = connection.query(query).getRecords(); 

    List<O> result = new ArrayList<O>(); 
    for (SObject record : records) { 
     result.add((O) record); 
    } 
    return result; 
} 
+3

Spiega cosa stiamo guardando, piuttosto che pubblicare un muro di codice. Grazie. – Andrew

Problemi correlati