Hello Friends, today I am going to show you an example that explains how to fetch all fields of any sObject using dynamic SOQL Query in Apex.
In many scenarios you have to get all fields of the sobject, when a large number of fields are available of an object, it’s tough to query fields one by one in the Apex Class.
Also Check this: Sharing records by Apex in Salesforce
Highlights Points :
- Dynamic SOQL refers to the creation of a SOQL string at run time with Apex code.
- Use Database.query(stringQuery); for query.
- No need to cast from a generic sObject to a concrete sObject.
- Have the same governor limits as static queries.
Example :
Here we will query account all fields and debug the data
DyanmicQueryDataCtrl.cls :
public class DyanmicQueryDataCtrl {
public static void DyanmicQueryMethod(){
Set<String> SobjectFields = Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap().keySet();
List<String> fieldsInList = new List<String>(SobjectFields);
List<Account> accList = Database.query('SELECT ' + String.join(fieldsInList, ',') + ' FROM Account');
System.debug('accList '+accList);
}
}
DyanmicQuerySearchTextCtrl.cls: In this example, we are searching text in dynamic SOQL Query.
public class DyanmicQuerySearchTextCtrl {
public static void DyanmicQuerySearchTextMethod(){
String query = 'SELECT Id, Name FROM Account WHERE Type = \'Customer - Direct\' LIMIT 1';
Account acc = Database.query(query);
System.debug('acc data=> '+ acc);
}
}
Reference :
What’s your Reaction?
+1
+1
+1
+1
1
+1
2
+1