You need to sign in to do that
Don't have an account?
degmo
Help with Dynamic SOQL
Hello All,
I need to build a dynamic SOQL where clause based on 15 fields and wanted to see if anyone can recommend a more efficient approach than what I have below:
I need to build a dynamic SOQL where clause based on 15 fields and wanted to see if anyone can recommend a more efficient approach than what I have below:
List<Drive__c> lstDrive = [SELECT Id, field1, field2, field3, field4, field5, field 6, field 7 FROM Drive__c where Id=:currentId LIMIT 1]; If(!lstDrive.isEmpty()){ Drive__c currentDrive = lstDrive[0]; String myQuery = 'SELET Id FROM Account Where '; if(currentDrive.field1 != null) { myQuery += 'field1 >= ' + currentDrive.field1 + ' AND '; } if(currentDrive.field2 != null) { myQuery += 'field2 >= ' + currentDrive.field2 + ' AND '; } if(currentDrive.field3 != null) { myQuery += 'field3 <=' + currentDrive.field3 + ' AND '; } . . . . } List<Account> result = Database.query(myQuery);Basically, I have 15 such 'if' blocks that build the where clause. Any suggestions or recommendation would be greatly appreciated.
Basically, you run a for loop on the lstDrive and build the query
Please take a look at this post for sample code
Let me know if this helps, if it does, please mark this answer as best so that others facing the same issue will find this information useful. Thank you
before try following code we are assuming that in contact and account both have same fields like Field_1_c,Field_2_c,... etc.
Testing Apex Code let me know if it helps you and marking it as best.
Thank you
If you use always the same fields and your clauses are all with AND, you could try something like that:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_soql.htm