Thursday 7 August 2014

Sales force SOQL : query to fetch all the fields from object



You have to specify the fields, if you want to build something dynamic the describeSObject call returns the metadata about all the fields for an object, so you can build the query from that.


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

String theQuery = 'SELECT ';
for(Schema.SObjectField s : fldObjMapValues)
{
   String theName = s.getDescribe().getName();
   // Continue building your dynamic query string
   theQuery += theName + ',';
}

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

// Finalize query string
theQuery += ' FROM Account LIMIT 2';

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

System.Debug('*******************'+accounts);