2

I'm trying to form a query in SOQL.

In scheduler ..

 sch.accountdList = AccList;  
 sch.query = 'SELECT id from Account where ID IN :'; 
 Database.executeBatch(sch,200);

and in Batch start..

 query=query+AccList;
 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!

1
  • 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, 2016 at 7:12

3 Answers 3

1

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.

4

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);
1
  • 1
    Thanks for helping. This worked for me.
    – MnZ
    Sep 20, 2023 at 4:13
2

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, ',') + ')';
1
  • 1
    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! Apr 26, 2020 at 18:10

You must log in to answer this question.

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