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

Hi @averyckrauss,

 

Filter means the condition/query, to get perform the CRUD operations.

Example: active=true

 

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