4
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

2 Answers 2

9

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.

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

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.

You must log in to answer this question.

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