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!

  • 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
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

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, ',') + ')';

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.