I'm trying to form a query in SOQL.

In scheduler ..

 sch.accountdList = AccList;  
 sch.query = 'SELECT id from Account where ID IN :'; 

and in Batch start..

 return Database.getQueryLocator(query);

This gives me this error

Only variable references are allowed in dynamic SOQL/SOSL

So I tried to avoid ":"

In scheduler again..

 sch.accountdList = AccList;  
 sch.query = 'SELECT id from Account where ID IN /''; 

I get this error:

mismatched character 'EOF' expecting

How should I form the query? Where am I going wrong?

Thanks in advance!

  • why you need acclist in separate variable ? you can just add like sch.query = 'SELECT id from Account where ID IN : AccList'; – Ratan Paul Sep 16 '16 at 7:12

I was also facing same kind of issue. Please find below code snippet to work.

Scheduler class: sch.accountList = accountList;

batch class

global List accountList = new List(); start() { query = 'select id from account where id in :accountList'; }

This is working for me.


In dynamic SOQL binding (using the : followed by the name of a variable that is in scope) does work, but only for simple names (no dotted expressions).

So given:

sch.accountdList = AccList;  
sch.query = 'SELECT id from Account where ID IN :';

you could execute the query using:

Id[] ids = sch.accountdList;
String soql = sch.query + 'ids';
return Database.getQueryLocator(soql);

Usually with the IN operator you have multiple entries. Keith has already covered the appropriate way to merge in the variable by reference. Might as well show how to merge in the literal values as well.

The reason your strategy there fails to compile is that you use the wrong slash to escape your quote (/' instead of \'), so your string is already closed by the time you hit the next single quote(') character.

I would do something more like:

List<String> literals = new List<String>();
for (Id value : accIdList) literals.add('\'' + value + '\'');
String soql = 'SELECT Id FROM Account WHERE Id IN ' +
    '(' + String.join(literals, ',') + ')';
  • Had to pass Set in where clause for the batch's constructor that was taking String as parameter. Took me hours and each time it was either variable doesn't exist or variable references are allowed in dynamic soql/sosl exception, until I found this thread and this answer. Thanks a ton! – Khushboo Dua Apr 26 '20 at 18:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.