Background script to copy existing field to new field within the same table?

averyckrauss
Tera Contributor

I am attempting to update all user records to copy the current usernames (user_name) to a new blank field (u_old_user_id) in the same table (sys_user).  The script below seems to work to update the records, however when run as a background script it is only updating a single user record instead of all users in the sys_user table.  Is there a mistake in the script that is causing it to only update a single record?

 

var gr = new GlideRecord('sys_user');


gr.query();


while (gr.next()) {


var x = gr.getValue('user_name');


if (x) {


gr.setValue('u_old_user_id', x);


gr.update();


}


}

 

 

1 ACCEPTED SOLUTION

Karthiga S
Kilo Sage

Hi @averyckrauss 

 

Restructure the code like below. "If" is causing one record update.

var gr = new GlideRecord('sys_user');
gr.query();
while(gr.next()) {
gr.u_old_user_id = gr.user_name;
gr.update();
}

Please mark it Correct and Hit Like if you find this helpful!

 

Regards,

Karthiga

View solution in original post

5 REPLIES 5

Karthiga S
Kilo Sage

Hi @averyckrauss 

 

Restructure the code like below. "If" is causing one record update.

var gr = new GlideRecord('sys_user');
gr.query();
while(gr.next()) {
gr.u_old_user_id = gr.user_name;
gr.update();
}

Please mark it Correct and Hit Like if you find this helpful!

 

Regards,

Karthiga

Worked like a charm, thank you!

Sagar Pagar
Tera Patron

Hi @averyckrauss,

 

Try this updated scripts:

var userRecord = new GlideRecord('sys_user');
userRecord.addEncodedQuery("add_filter_here");
userRecord.query();
while (userRecord.next()) {

	if (!userRecord.getValue('user_name')) {
		userRecord.setValue('u_old_user_id', userRecord.getValue('user_name'));
		userRecord.setWorkflow(false);
		userRecord.update();
		
	}

}


If my response helps to solve your issue. Kindly mark it as helpful & correct. It will be helpful for future readers.
Thanks,
Sagar Pagar

The world works with ServiceNow

Thanks for the response.  What would the appropriate filters (or examples of filters) be for this script?