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 

While SOQL Query returns > 0, do...

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
 
Nathan Prats 22Nathan Prats 22
Something like this i mean
 
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];
        
        Integer X = [SELECT Id,OwnerId,Parent.OwnerId 
                     FROM Account 
                     WHERE Account_Owner_Parent_Owner__c = TRUE 
                     AND IsExcludedFromRealign = FALSE];
        
        do {
            for(Account Acc : AccList){    
                Acc.OwnerId = Acc.Parent.OwnerId ;
            };
                } while (X < 0);
        
        update AccList; }
    
}

 
Steven NsubugaSteven Nsubuga
This is quite a pickle you're in!!
My suggestion would be to create a Process that runs whenever a new account is created or edited, to assign the owner to the parent owner.
That would take care of future records going forward. Then you would only have the old records to take care of, maybe by repeatedly running your current code. It is not an elegant solution, but that's what I think for now. Hopefully someone can suggest a better solution.