+ Start a Discussion
Dano BlevinsDano Blevins 

Batched code to find records without attachment

We have a custom object called Provider_Case__c, I need to find every Provider case that does not have an attachment called 'Licensing Inspection Report'
We have a lot of Provider_Case__c records and tons of attachments so if you run this without batch you will hit SOQL 50K limits. This is something I just need to run as a one off item to identify these (so we don't need automation or trigger) and if possible just have it all dump into a debug file I can download.
The following code not working and need help figuring out why.
global class ProviderCasesWithoutAttachments implements Database.Batchable<sObject>
    Set<Id> setAttachmentParentId = new Set<Id>();
    Global Database.QueryLocator start(Database.BatchableContext BC) {
       String query = 'SELECT ParentId from Attachment where parent.type = \'Provider_Case__c\' AND CreatedDate >= 2017-01-01T00:00:00Z AND Name =\'Licensing Inspection Report\' ';
       System.debug('query -> ' + query);
       return Database.getQueryLocator(query);
    Global void execute(Database.BatchableContext BC, List<SObject> records) {
    List<Attachment> attchList = (List<Attachment>)records;
    for(Attachment a : attchList ){
        List<Provider_Case__c> lstPC =
            [SELECT Id, Name, RecordType_Name__c
            FROM Provider_Case__c
            WHERE (RecordType_Name__c = 'Annual Compliance'OR RecordType_Name__c = 'Finalized'OR RecordType_Name__c = 'Monitoring Visit') AND ID NOT IN : setAttachmentParentId];
   System.debug('These PCases Are: ' + lstPC); }
   Global void finish(Database.BatchableContext BC) {

Christan G 4Christan G 4
Hi Dano, I hope you are well. What is the error being returned when you run this batch?