Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.
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

share|improve this question

2 Answers 2

up vote 6 down vote accepted

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.

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

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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