Wednesday, 1 August 2012

Retrieing all fields without specifying field names in SOQL Query

I am trying to explain how to get all fields data from an sobject without specifying particular fields  in query(SOQL) in Apex.
Because we cannot use '*' symbol in SOQL query to retrieve all fields from an sobject as in oracle(sql) in Apex.For every field to query  in
sobject  we need to specify  field names.So in the case of selecting all fields we need to write all fields in SOQL ,to avoid this
the  dynamic SOQL preparation with all fields using dynamic apex snippet is helpful.
Here just we need to prepare a string with all fields using dynamic apex with comma separation and we  insert this in 'SOQL' query.

Map<String, Schema.SObjectField> M = Schema.SObjectType.Account.fields.getMap();
public List<sObject> lstaccount{get;set;}
 Public List<string> fieldlst{get;set;}
Public List<Schema.SobjectField> lstfields{get;set;}

string fieldnames=' ';
            fieldlst=new List<String>();
            fieldnamestoquery=new List<String>();
            for(Schema.SObjectField s:m.values()){
                    Schema.DescribeFieldResult sfield=s.getDescribe();
                    fieldnames+=s+',';  //Here we concatenating all field names with comma seperation for preparing SOQL query
                   fieldlst.add(string.valueof(sfield.getName()));//Field list contains apinames all fields of Account
            fieldnames=fieldnames.substring(0,fieldnames.length()-1);//Fieldnames string contains all the fields with comma separation

            string query='select '+fieldnames+' from Account';//Here we are preparing string query(dynamic SOQL using "fieldnames" string)
            if(query!=null && query!='')
                    lstaccount=database.query(query);//Here we will get all field values from account.

No comments:

Post a Comment