Salesforce Apex auto create soql

Posted by ExiaHuang on August 4, 2017

Salesforce Apex auto create soql

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Map<String, Schema.SObjectType> smap = Schema.getGlobalDescribe();

for(Schema.SObjectType sobj : smap.Values()){
    Schema.DescribeSObjectResult sr = sobj.getDescribe();
    // field
    Map<String, Schema.SObjectField> fmap = sr.fields.getMap();

    List<string> fields = new List<string>();
    for (String fieldKey : fmap.keySet()) {
        Schema.SObjectField f = fmap.get(fieldKey);
        Schema.DescribeFieldResult fr = f.getDescribe();
        fields.add(fr.getName());

        // if(!fr.isCustom() ) continue;
        // System.debug('***** field is Custom: ' + fr.isCustom());
        // System.debug('***** field label: ' + fr.getLabel());
        // System.debug('***** field API reference name: ' + fr.getName());
        // System.debug('***** field type: ' + fr.getType());
        // System.debug('------>fr ' + fr);
    }

    String soql = 'SELECT ';
    soql += string.join(fields,' , ');
    soql += ' FROM ' + sr.getName();
    System.debug(soql);

}