When I have a Set of Id's and I want to do a dynamic SOQL query that I want to use it in for an IN comparison, I have to convert the Set to string in the format of:
('id1','id2',id3',...)
The way I do it works, but is not particularly elegant, so I'm wondering if anyone has come up with a better way. Am I missing something? Is there something out there that can just turn a set or list into the properly formatted string?
Here's my code (yes, my example isn't dynamic SOQL, but I've used this several times in dynamic SOQL):
Map<Id, Account> accts = new Map<Id, Account>([SELECT Id FROM Account]);
String idString = '(\'';
for (Id thisId : accts.keySet()) {
idString += thisId + '\',\'';
}
idString = idString.substring(0,idString.length()-2); //<--this is the bit I hate doing
idString += ')';
String q = 'SELECT Id FROM Contact WHERE AccountId IN ' + idString;
List<Contact> cts = Database.query(q);