0

I'm trying to run a batch that makes user Inactive if logged in past 2 hours. It runs in to error ": line 1:74 no viable alternative at character" when i try to run this batch. I doubt if the SOQL query condition for Lastlogindate time is correct. Can someone please point to me in right direction?

global class ScheduleInactiveUser Implements Schedulable,  Database.Batchable<sObject> {
global void execute(SchedulableContext sc) {
        Database.executeBatch(this, 2000); 
         }
global Database.QueryLocator start(Database.BatchableContext BC) {
        string query = 'Select Id, LastLoginDate, IsActive, Name From User Where Profile_Name__c ="Portal JIT User" AND LastLoginDate >= :System.Now().addHours(-2)';
        return Database.getQueryLocator(query);
         }
global void execute(Database.BatchableContext BC, List<sObject> scope) {
        List<User> UserList = (List<User>) scope;
        for(User c : UserList){
         c.IsActive = False;
            } 
        update UserList;
         }
    global void finish(Database.BatchableContext BC) {
         }
}

Thank you

1 Answer 1

3

The double quotes are what the error is complaining about, though it is hard to see the double quote in '"' in the error message. The double quotes appear in Where Profile_Name__c ="Portal JIT User".

Dobule quotes shouldn't be used on the platform in general. There are some exceptions (the JSON and XML parsers can handle them), but they must not appear in general code nor in queries (regular or dynamic) unless they're contained in a string literal (e.g. WHERE MyTextField__c = 'Mr. MacDonald, "Mayor" of Hooverville').

Replace those double quotes with escaped single quotes, i.e. \', and that error should disappear.

The next issue you'd run into is trying to bind system.now().addHours(-2). Dynamic queries can only handle simple variable binds. Bring that calculation out of your query, into its own variable, and then bind just that variable.

3
  • 1
    Don't forget dot references not allowed in dynamic SOQL.
    – Adrian Larson
    Commented Mar 3, 2021 at 18:31
  • @AdrianLarson What? Me, forget? never! (answer edited).
    – Derek F
    Commented Mar 3, 2021 at 18:36
  • Thanks so much, I was able to run to run the batch
    – Saaki
    Commented Mar 3, 2021 at 22:18

You must log in to answer this question.

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