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
Tony GarandTony Garand 

updating all contact owners to match account owners via developer console

Hello Developer Community!

I am tasked with updating my company's whole database so that the contact owners match the Account owners. There are around 5k records to change and it would be taxing to go through an excel sheet and change them and re-load them via dataloader. So, I figured some code could do the trick in the Developer Console via Execute Anonymous Window. Would the code below work?

User-added image

Let me know your thoughts and thank you for your time.

Tony Garand
 
Raj VakatiRaj Vakati
Hi Tony ,
Use this code .
List<Contact> conUpdate = new List<Contact>();
for(Contact c: [Select id,OwnerId , Account.Owner.Id from Contact]){
    If(c.OwnerId !=c.Account.Ownerid){
        If(c.Account.Ownerid!=null){
            c.OwnerId = c.Account.Ownerid ;
            
            conUpdate.add(c);
        }
    }
    
}
update conUpdate ;

 
Deepankar ChandaDeepankar Chanda
Hi Tony, 

for(contact c:[SELECT Id, AccountId, Ownerid, Account.ownerid from contact])
Change to 
for(contact c:[SELECT Id, AccountId, Ownerid, Account.ownerid from contact limit 5000])

And change the Query from
SELECT Id, AccountId, Ownerid, Account.ownerid from contact
to
SELECT Id, AccountId, Ownerid, Account.ownerid from contact where  AccountId != null limit 5000

Rest is fine.

 
List<contact> contactsToChangeOwner = new List<contact>();
for(contact c:[SELECT Id, AccountId, Ownerid, Account.ownerid from contact where  AccountId != null limit 5000]){
 
    if(c.ownerid!=c.Account.ownerid){
        c.ownerid = c.Account.ownerid;
        contactsToChangeOwner.add(c);
    }
}

update contactsToChangeOwner;
RKSalesforceRKSalesforce
If you have huge no of records then you can use batch Apex:
global class BatchName implements Database.Batchable<sObject>, Database.Stateful{

	   global final String query;
	   
	List<contact> contactsToChangeOwner = new List<contact>();
	global final String Query ='SELECT Id, AccountId, Ownerid, Account.ownerid from contact where  AccountId != null';
	   global Database.QueryLocator start(Database.BatchableContext BC){
		  return Database.getQueryLocator(query);
	   }
	   
	   global void execute(Database.BatchableContext BC, List<sObject> scope){
		
		for(Contact con: scope){
			if(con.ownerid!=con.Account.ownerid){
				c.ownerid = c.Account.ownerid;
				contactsToChangeOwner.add(c);
			}			
		}
		update contactsToChangeOwner;
	   
	   }
	   

	global void finish(Database.BatchableContext BC){   
	   
	}

Please let me know if it helped.
Tony GarandTony Garand
Deepankar why would I limit the amount of records I want to change? It is over 5k records (5,400) that have different account / contact owners. And we have 7,788 records in total that I will probably just run the command on all of them.
Ramakant would the batch command be best for running this many records? or can I just use Rajamohan.Vakati's code?
Deepankar ChandaDeepankar Chanda
Hello Tony,

You can ignore limit 5K in the query (I had given as you mentioned you have around 5K so, limiting to 5K only) & instead you can keep what I mentioned below.

There is not much diff between Rajamohan.Vakati's code & mine. Both are same only in my query itself I am taking out the leads who are not associated with any account (AccountIds) record where as in his it's getting checked with in the loop in a if condition.

You can use anyone's code both will give same result.

My modified code
List<contact> contactsToChangeOwner = new List<contact>();
for(contact c:[SELECT Id, AccountId, Ownerid, Account.ownerid from contact where  AccountId != null ]){
 
    if(c.ownerid!=c.Account.ownerid){
        c.ownerid = c.Account.ownerid;
        contactsToChangeOwner.add(c);
    }
}

update contactsToChangeOwner;

Let me know if my explantion help you.
Tony GarandTony Garand
Deepankar Chanda,

Thank you for the follow up! Just to clarify this code will make the owner in red the owner of the contacts assocated with the accounts?

User-added image

User-added image
Deepankar ChandaDeepankar Chanda
Hello Tony,

You are welcome & yes account owner will be set to associated contact's owners if it's different than account owner.

 
Tony GarandTony Garand
When I ran the script I recieved an Error "Apex CPU limit exceeded"

User-added image

Should I use Ramakant's Batch Command?
Deepankar ChandaDeepankar Chanda
Hello Tony, it's strange your code should not hit the CPU limit just cuz of this code only you are quering & updating the data.
For ref https://help.salesforce.com/articleView?id=000232681&language=en_US&type=1

But yes you can use the batch command, use the below code I changed few lines.
 
global class RunAccountBatch implements Database.Batchable<sObject>, Database.Stateful{

	//global final String query;
	   
	List<contact> contactsToChangeOwner = new List<contact>();
	global final String Query ='SELECT Id, AccountId, Ownerid, Account.ownerid from contact where  AccountId != null';
	   global Database.QueryLocator start(Database.BatchableContext BC){
		  return Database.getQueryLocator(query);
	   }
	   
	   global void execute(Database.BatchableContext BC, List<contact> scope){
		
		for(contact con: scope){
			if(con.ownerid!=con.Account.ownerid){
				con.ownerid = con.Account.ownerid;
				contactsToChangeOwner.add(con);
			}			
		}
		update contactsToChangeOwner;
	   
	   }
	   

	global void finish(Database.BatchableContext BC){   
	   
    }
}
remember you have to create an apex class with the batch class name "RunAccountBatch" and then go to Anony Execute window & run the below two lines of code: 
 
RunAccountBatch myBatch = new RunAccountBatch();
database.executeBatch(myBatch);

Please let me know if it help you out.
 
Deepankar ChandaDeepankar Chanda
Hello Tony, Let me know if the explanation helped you out?
If yes, then please approve it & to keep the board clean mark it as answered.
Colby JuarezColby Juarez
Deepankar Chanda I am attempting to run this and I am experiencing the Apex CPU time limit exceeded would you be able to best assist? I have got some of my contacts to update but not others