Search code examples
salesforcesoql

Custom Label value not working in SOQL Query


I am trying to use custom label value in SOQL Query. Query is not accepting custom label value. it is expecting number.

Integer num_days = Integer.valueOf(System.Label.Num_of_Days); Select id, name FROM contact WHERE LastModifiedDate >= LAST_N_DAYS :num_days

Thanks, Anil Kumar


Solution

  • The full syntax of the "constant" you're using already has a semicolon in it: LAST_N_DAYS:7 etc. The whole thing has to be a text known at compile time, not just the part before :

    This won't even compile, with 1 or 2 semicolons.

    Integer x = 7;
    List<Account> accs = [SELECT Id FROM Account WHERE CreatedDate = LAST_N_DAYS:x];
    System.debug(accs);
    

    You'll need to use dynamic SOQL or use your custom label to construct a date variable

    String x = '7';
    List<Account> accs = Database.query('SELECT Id FROM Account WHERE CreatedDate = LAST_N_DAYS:' + x);
    System.debug(accs);
    
    DateTime cutoff = System.today().addDays(- Integer.valueOf(x));
    System.debug(cutoff);
    System.debug([SELECT Id FROM Account WHERE CreatedDate <= TODAY AND CreatedDate >= :cutoff]);