0

I hope someone can help to convert my class to batch job. This is the first time that I will create a batch job and only a newbie in apex coding.

Here is my class which is working but hitting the DML limit as there are more than 10k to insert.

global class Eisai_BatchInsertAcctList implements Database.batchable<sObject>, Database.Stateful { 
    global string query = 'Select Account_Name_String__c, Account_Owner__c FROM Account_Territory_Mapping__c
        WHERE Account_Name_String__c != Null 
        AND Account_Owner__c !=Null;

    global Iterable<sObject> start(Database.BatchableContext info){
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext info, List<Account_Territory_Mapping__c> scope){
        List<Account_List_vod__c> ToInsertAcctList = new List<Account_List_vod__c>();

        for(Account_Territory_Mapping__c  Atm : scope){
            if(Atm.Account_Name_String__c != Null && Atm.Account_Owner__c !=Null){
                Account_List_vod__c AccList = new Account_List_vod__c();
                AccList.Name = 'HO_' + Atm.Account_Name_String__c;
                AccList.OwnerId = Atm.Account_Owner__c;
                ToInsertAcctList.add(AccList);
            }   
        }
        Database.insert(ToInsertAcctList,false);
    }
    global void finish(Database.BatchableContext info){
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'[email protected]'};
            mail.setToAddresses(toAddresses);
        mail.setSenderDisplayName('Salesforce Support');
        mail.setSubject('Eisai_BatchInsertAcctList Batch Job Run Complete');
        System.debug('Insert Account List Count: ' + ToInsertAcctList.size());
    }       
}

Below is the error messasge which I encountered:

Error: line breaks not allowed in string literals

3
  • In your Global String Query put everything on a single line. That's what the error message is telling you.
    – crmprogdev
    Commented Jul 21, 2016 at 13:57
  • I cleaned up the indentation for you so it's easier for us to read.
    – sfdcfox
    Commented Jul 21, 2016 at 16:35
  • Thanks for sharing your email address! Never, ever, hard code your own (or anyone else's) email address into email alerts. You will regret it eventually.
    – Adrian Larson
    Commented Jul 21, 2016 at 17:02

2 Answers 2

2

Your class was close, but I've included some comments regarding mistakes in your code. The below code is fixed and should (probably) work.

global class Eisai_BatchInsertAcctList implements Database.batchable<sObject>, Database.Stateful {
    // Keeping track of total records inserted
    Integer totalRecordsInserted = 0, totalRecordsFailed = 0;

    // Unless you need dynamic queries, just use inline queries.
    global Iterable<sObject> start(Database.BatchableContext info) {
        return Database.getQueryLocator(
            [Select Account_Name_String__c, Account_Owner__c FROM Account_Territory_Mapping__c
             WHERE Account_Name_String__c != Null AND Account_Owner__c !=Null]);
    }

    global void execute(Database.BatchableContext info, List<Account_Territory_Mapping__c> scope){
        List<Account_List_vod__c> ToInsertAcctList = new List<Account_List_vod__c>();
        // Removed if-- the query already selected records that matched the criteria
        for(Account_Territory_Mapping__c  Atm : scope){
            // Don't use temporary variables, prefer inline field assignments
            ToInsertAcctList.add(
                new Account_List_vod__c(
                    Name = 'HO_' + Atm.Account_Name_String__c,
                    OwnerId = Atm.Account_Owner__c));
        }
        // Remember to verify which records actually inserted:
        for(Database.SaveResult result: Database.insert(ToInsertAcctList,false)) {
            if(result.isSuccess()) {
                totalRecordsInserted++;
            } else {
                totalRecordsFailed++;
            }
        }
    }
    global void finish(Database.BatchableContext info){
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        // Does not use daily mail limits!
        mail.setTargetObjectId(UserInfo.getUserId());
        mail.setSaveAsActivity(false);

        mail.setSenderDisplayName('Salesforce Support');
        mail.setSubject('Eisai_BatchInsertAcctList Batch Job Run Complete');

        // You want to send a body, not a debug statement that you'll lose
        mail.setPlainTextBody(
            'Records successfully inserted: ' + totalRecordsInserted + '\n' +
            'Records failed insertion: ' + totalRecordsFailed);
        // You need to remember to send the email.
        Messaging.sendEmail(new Messaging.Email[] { mail });
    }
}

To run in Execute Anonymous, simply use:

Database.executeBatch(new Eisai_BatchInsertAcctList());
2
  • Hi Sir, it works! Thank you so much, but I have question also, Im trying to insert the Account List Item (Details) on the Account List(Master) created.
    – Mariones
    Commented Jul 21, 2016 at 20:14
  • @Noiram I'm not sure what you're asking. If you're trying to map the Account_list_vod__c to the Account_Territory_Mapping__c, it's probably just as simple as adding a line of code in the new Account_List_vod__c( area.
    – sfdcfox
    Commented Jul 21, 2016 at 21:13
3

Your second line: global string query ....

This is a string, but it breaks over multiple lines. To make it work, you need something like:

global string query = 
    'SELECT Account_Name_String__c, Account_Owner__c ' + 
    'FROM Account_Territory_Mapping__c  ' + 
    'WHERE Account_Name_String__c != Null ' + 
    'AND Account_Owner__c !=Null';

Notice how each line closes the string and specifies there is more to come with the + sign.

1
  • ok, can you please guys tell me how to execute the batch job in Anonynmous window to test if that is working? This should insert more than 10k records right?
    – Mariones
    Commented Jul 21, 2016 at 15:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .