function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Terry411Terry411 

Batch APEX Query IN clause

I have a batch process setup that could process upwards of 300,000 contact records.  Do to governor limits, I've setup my code to use batch apex.  All my code is working except for the query call.  

 

TerritoryRefreshBatch trb = new TerritoryRefreshBatch();
trb.query = 'SELECT Id, AccountId, MailingPostalCode, IM_Territory__c, EM_Territory__c, RatingOverride__c ' +
							'FROM Contact ' +
							'WHERE MailingPostalCode IN \'' + zCodes + '\'' +
							'AND RecordTypeId IN \'' + rtIds + '\'';
string batchId = Database.executeBatch(trb);

Syntactically, it's saves but when I exectuce the batch I get a "First error: unexpected token: '{012d0000000Ssj3AAC, 012d0000000Ssj8AAC}'".  That token is my set<string> of values I need for the dynamic query.

 

If I modify my query to pull a specific record, everything processes fine.  So, my question is, how do I structure my query string when using the "IN" clause?

 

Best Answer chosen by Admin (Salesforce Developers) 
Terry411Terry411

@Avin  Thank you!  That got me close enough to get it working.  I used what you gave me and then just had to define the two  variables in the controller and set them. 

 

trb.zCodes = zCodes;
trb.rtIds = rtIds;
trb.query = 'SELECT Id, AccountId, MailingPostalCode, IM_Territory__c, EM_Territory__c, RatingOverride__c ' +
				'FROM Contact ' +
				'WHERE MailingPostalCode IN :zCodes ' +
				'AND RecordTypeId IN :rtIds';
string batchId = Database.executeBatch(trb);

 First few lines of the controller:

global class TerritoryRefreshBatch implements Database.Batchable<sObject>, Database.Stateful{
		
	global string query;
	global set<string> zCodes;
	global set<string> rtIds;

 

All Answers

AvinAvin

try this

 

trb.query = 'SELECT Id, AccountId, MailingPostalCode, IM_Territory__c, EM_Territory__c, RatingOverride__c FROM Contact WHERE MailingPostalCode IN: zCodes AND RecordTypeId IN: rtIds';

Terry411Terry411

@Avin  Thank you!  That got me close enough to get it working.  I used what you gave me and then just had to define the two  variables in the controller and set them. 

 

trb.zCodes = zCodes;
trb.rtIds = rtIds;
trb.query = 'SELECT Id, AccountId, MailingPostalCode, IM_Territory__c, EM_Territory__c, RatingOverride__c ' +
				'FROM Contact ' +
				'WHERE MailingPostalCode IN :zCodes ' +
				'AND RecordTypeId IN :rtIds';
string batchId = Database.executeBatch(trb);

 First few lines of the controller:

global class TerritoryRefreshBatch implements Database.Batchable<sObject>, Database.Stateful{
		
	global string query;
	global set<string> zCodes;
	global set<string> rtIds;

 

This was selected as the best answer