-1

Please help me how to get value for split values "valueArray[1]" in below query.

I am trying to fetch the records, but i found issue in writing dynamic query. Please let me know if I am missing syntax in belowsoql query.

List<String> valueArray = new List<String>();
    for(String strValues : listOfValues) {
     valueArray = strValues.split('-');
     Integer intValue = Integer.ValueOf(valueArray[1]);
    
    for(sObject sObj : Database.query('SELECT Id FROM ' + valueArray[0] + ' WHERE CreatedDate < Last_N_Days:intValue ')) {
    }
1
  • Welcome to SFSE! valueArray is a String in this example, you cannot access the index of a String. What does listOfValues look like, something like {'Account-20', 'Contact-10'}` i.e look for Accounts created in last 20 days, look for Contacts created in last 10 days?
    – TSmith
    Dec 21, 2021 at 17:15

1 Answer 1

1

Bind variables in Dynamic Apex do not support complex expressions (e.g. accessing an array), so you just need to use normal string concatenation:

for(sObject sObj : Database.query('SELECT Id FROM ' + 
    String.escapeSingleQuote(valueArray[0]) + 
    ' WHERE CreatedDate < Last_N_Days:' +
    String.escapeSingleQuote(valueArray[1]))) {
5
  • 3
    SOQL injection attack prevention encoding should be added here...
    – Phil W
    Dec 21, 2021 at 17:13
  • @PhilW Fair enough. I try not to assume too much about where the input comes from, but as a general best practice, one should definitely escape quotes.
    – sfdcfox
    Dec 21, 2021 at 17:18
  • in valueArray, there are multiple objects and it's related number but I am getting only one sobject from valueArray[0], after that execution is being stopped. I have checked in debug logs. Dec 21, 2021 at 18:47
  • @sfdcfox if the OP is looking to query many objects (unknown from List), how would we tackle or improve this from platform limit perspective?
    – TSmith
    Dec 22, 2021 at 11:56
  • 1
    @TSmith I don't want to assume too much, the query looks like it's incorrect anyways (they probably meant = instead of <). If that's true, Database.getUpdated returns records created and updated within a time window, for free (no governor limits are used aside from CPU/heap). If they need to query hundreds of objects, then context will matter. Might need to call it from a loop client-side, or batchable, etc. It's too vague to give a specific solution.
    – sfdcfox
    Dec 22, 2021 at 13:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .