Apex 批处理将 account owner 转移,同时实现关联的 opp 和 case 转移
实现和 mass transfer account 一样的功能:
global class AccountBatchScript implements Database.Batchable<sObject>,Schedulable{String query;Id oldOwnerId = 'xxxxxxxxxxxx';Id newOwnerId = 'yyyyyyyyyyyy';List<Id> AccountIds = new List<Id>();List<String> AccountNames = new List<String>{'TestAccount241112','TestAccount241113'};global AccountBatchScript() {query = 'SELECT Id,Name FROM Account WHERE OwnerId=\''+oldOwnerId+'\' AND Name IN : AccountNames';if(Test.isRunningTest()) query += ' LIMIT 10';}global Database.QueryLocator start(Database.BatchableContext BC) {return Database.getQueryLocator(query);}global void execute(Database.BatchableContext BC, List<sObject> scope) {system.debug('scope.size()'+scope.size());List<Account> accountsToUpdate = new List<Account>();for(Account acc : (List<Account>)scope) {acc.OwnerId=newOwnerId; accountsToUpdate.add(acc);AccountIds.add(acc.Id);}System.debug('accountsToUpdate ' + accountsToUpdate);System.debug('accountsToUpdate size ' + accountsToUpdate.size());update accountsToUpdate;List<Opportunity> openOpps = [SELECT Id FROM Opportunity WHERE AccountId IN :AccountIds];for (Opportunity opp : openOpps) {opp.OwnerId = newOwnerId;}update openOpps;List<Case> openCases = [SELECT Id FROM Case WHERE AccountId IN :AccountIds AND ((IsClosed = false AND OwnerId = :oldOwnerId) OR IsClosed = true)];for (Case c : openCases) {c.OwnerId = newOwnerId;}update openCases;}global void finish(Database.BatchableContext BC) {}public void execute(SchedulableContext ctx){AccountBatchScript batch = new AccountBatchScript();Database.executeBatch(batch, 10);}}