Salesforce database query language is SOQL.When writing queries one of the tedious tasks developers face is specifying each and every field you want in queries.Unlike SQL ,SOQL doesnt allow you to query all the fields by using "*" .Salesfroce . Salesforce may have their own reasons for not allowing "*" such as querying all the fields always may affect the performance as well as it may cause you run into view state limits in visualforce pages.
All though SOQL doesn't allow you the "*" operator you can archive the same using Dynamic SOQL and the Salesforce meta data api.
Lets assume your object Name is MyObject__c
Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe(); Map <String, Schema.SObjectField> fieldMap = schemaMap.get('MyObject__c').getDescribe().fields.getMap(); List<MyObject__c> results; String Query = 'Select';
//loop through all object fields and add them to select clause
for(Schema.SObjectField sfield : fieldMap.Values()) { schema.describefieldresult dfield = sfield.getDescribe(); String fieldApexName = dfield.getname(); if(Query.equals('Select')) { Query+=' '+fieldApexName; } else { Query+=' ,'+fieldApexName; } }
//optionally if you want parent object fields you have to mention each of them the explicitly
Query += ',PerentObject__r.FieldName__c '; Query+= ' From MyObject__c '
//Optionally if you have a condition they can be added as
Query+= ' where Name = myfirstRecord '
//return results
results = Database.query(Query);
Learn more about Dynamic SOQL .
Learn more about SOQL
great!
ReplyDelete