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
Nathan Prats 22Nathan Prats 22 

reassign

Hello, 

I created this piece of code that reassigns all accounts to the right owner based on the account hierarchy. 
The issue is that this code reassigns 1 node at a time. 

I'd like it to do this until the following query returns 0 : 
SELECT Id,OwnerId,Parent.OwnerId 
FROM Account 
WHERE Account_Owner_Parent_Owner__c = TRUE 
AND IsExcludedFromRealign = FALSE
Current Code
global class ReassignAccounts implements Schedulable {
    
    global void execute(SchedulableContext ctx) {
        List<Account> AccList = [SELECT Id,OwnerId,Parent.OwnerId FROM Account WHERE Account_Owner_Parent_Owner__c = TRUE AND IsExcludedFromRealign = FALSE];
        
        for(Account Acc : AccList){    
            Acc.OwnerId = Acc.Parent.OwnerId ;
        }
        
        update AccList; }
    
}

Can I add a while [SELECT Id,OwnerId,Parent.OwnerId FROM Account WHERE Account_Owner_Parent_Owner__c = TRUE AND IsExcludedFromRealign = FALSE] > 0, do ... ? 

Thanks, 

Nathan
 
Vladimir SaturaVladimir Satura
Hi Nathan,
depends on how many records you have in your org, I'll be best to create a batch for this.

Easiest way to do this is adding you logic to batch job, and at the end of the batch (finish method), you'll check for count on your query, and if it is > 0 you'll execute the same batch again from finish method. This will sort of create your 'while > 0' and batch will run until there are records with incorrect parent.

This will however makes a LOT of unnecessary reassigns and account updates and you will be updating owner on accounts back and forth for no reason.

Better solution (and way harder to code) is making the batch a little smarter, so it will know which records to process first, so it will start from the root of your hierarchy and will go level by level until it reaches all the leafs