[SalesForce] Dynamic soql : Unexpected token ‘{‘

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

Best Answer

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.

Related Topic