3
Set<Id> sId = new Set<Id>{};
sId.add('a0df000000063A9AAI');
sId.add('a0df00000006P2cAAE');
String squery = 'SELECT Id, Name FROM Engagement__c  WHERE Id IN:'+sId;
List<Engagement__c> lst = database.query(squery);   
System.debug('----list size:'+lst.size());

Im getting the following error

System.QueryException: unexpected token: '{'

Please helppppp! thanks

8

Syntax is wrong.

Either use this way :-

Set<Id> sId = new Set<Id>();

OR

Set<Id> sId = new Set<Id>{'a0df000000063A9AAI','a0df00000006P2cAAE'};

// no need to use '+sid;
String squery = 'SELECT Id, Name FROM Engagement__c  WHERE Id IN:sId';

// else is correct
List<Engagement__c> lst = database.query(squery);   
System.debug('----list size:'+lst.size());

Why it cannot be +sId?

Using this approach will lead to wrong SOQL syntax. For ex:

Query String will become:

SELECT Id, Name FROM Engagement__c  WHERE Id IN:{a0df000000063A9AAI,a0df00000006P2cAAE}

which is a wrong syntax for SOQL query.

  • It worked. thanks. Since sId is variable, so I was using as +sId. Why it cannot be +sId? – sfdcFanBoy May 7 '14 at 11:19
  • Have a look at here salesforce.com/us/developer/docs/apexcode/Content/… – highfive May 7 '14 at 11:21
  • @BruceLee updated answer for '+sid. – Ashwani May 7 '14 at 11:23
  • One is string concatenation, the other is parameter binding. – user6861 May 7 '14 at 16:57
3

Your set variable should declare like,

Set<Id> sId = new Set<Id>();

Also when you are using Dynamin SOQL there some considerations. You can put a List or Set variable inside the query, but not like string append as you are currently doing. Alter your query into

String squery = 'SELECT Id, Name FROM Engagement__c  WHERE Id IN:sId';

Make sure that the variable sId is in the scope of where the Database.query() is performed. You can get an idea about Dynamic query from here.

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.