I'm trying to pass a list of 1000 account IDs and retrieve their corresponding count of Contacts and write the results to a CSV file. I'm using the Anonymous Execute window to run the code below as I need to get this data from multiple Orgs without creating custom Apex classes.
List<Id> accountIds = new List<Id>();
// Add the hardcoded account IDs to the list
//Will be adding about 1000 accounts here
accountIds.add('00xxxxxxxxxxxxxxxxxxxxxx');
// Define a list to hold the queried data
List<Contact> contactList = new List<Contact>();
// Define a string to hold the CSV file content
String csvContent = 'Account ID,Number of Contacts,First Name,Last Name,Email\n';
// Query the data and assign it to a list of AggregateResult objects
List<AggregateResult> results = [SELECT COUNT(Id) numContacts, AccountId, MIN(FirstName) firstName, MIN(LastName) lastName, MIN(Email) email FROM Contact WHERE AccountId IN :accountIds GROUP BY AccountId];
// Loop through the results and create a new Contact object for each one
for (AggregateResult result : results) {
// Extract the values from the AggregateResult object and use them to create a new Contact object
Contact c = new Contact();
c.AccountId = (Id)result.get('AccountId');
c.FirstName = (String)result.get('firstName');
c.LastName = (String)result.get('lastName');
c.Email = (String)result.get('email');
contactList.add(c);
// Add the Account ID, number of contacts, and contact information to the CSV content
csvContent += c.AccountId + ',' + result.get('numContacts') + ',' + c.FirstName + ',' + c.LastName + ',' + c.Email + '\n';
}
// Write the CSV content to a file
String fileName = 'AccountContacts.csv';
Blob csvBlob = Blob.valueOf(csvContent);
ContentVersion cv = new ContentVersion();
cv.Title = fileName;
cv.PathOnClient = fileName;
cv.VersionData = csvBlob;
insert cv;
I'm getting an error as below
Line: undefined, Column: undefined Response to EXEC was : Bad Message 414 reason: URI Too Long . HTTP CODE[414]
Is there an efficient way to do this? I've been trying to pass 1000 account IDs at a time to retrieve their corresponding Contact count, but nothing seems to be working. I could potentially generate a report that provides this information, but thought I'd check if there is a programmatic way to do it.
Any inputs would be highly appreciated!