Script To Populate Reference Field
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-24-2021 07:35 AM
I have a table which has a string field called "u_created_by" which currently has "joe.smith" which is the users ID. I have since created a reference field for reporting purposes that is populating the "requestor" going forward. I am having trouble writing a script to do a one time update that would take the users ID from the string field, query the user table and populate the new reference field "requestor".
Any help is appreciated!
- Labels:
-
Scripting and Coding

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-24-2021 07:53 AM
Here is an example , might need some adjustment..
var grUser = new GlideRecord("sys_user");
grUser.addQuery('u_created_by','=','joe.smith');
grUser.query();
while (grUser.next()) {
grUser.requestor=grUser.u_created_by;
grUser.update();
}
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-24-2021 07:54 AM
Hi Nic,
Every table will have created and created by fields by default. Not sure about your exact requirement but to update the existing code you can try below code in lower instances.
Try below script:
var tableNam = new GlideRecord('TableName'); //Mention the table name
tableNam.addQuery('newReferenceFieldName','');//Mention the backend field name of the reference field.
table.setLimit(50); //Specify limit of record which query should return.
tableNam.query();
while(tableNam.next())
{
var user = new GlideRecord('sys_user');
user.addQuery('use_name',tableNam.u_created_by);
user.query();
if(user.next())
{
tableNam.newReferenceFieldName = user.sys_id; //Mention the new reference field name
tableNam.setWorkflow(false); // Aborts execution of business rules
tableNam.update();
}
}
Mark my response as correct/helpful if it helps.
Regards,
Rajesh M.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-24-2021 08:15 AM
Create fix script or write background script for this
updateRecords();
function updateRecords(){
var rec = new GlideRecord('tableName');
rec.addQuery('u_created_byISNOTEMPTY');
rec.query();
while(rec.next()){
var userRec = new GlideRecord('sys_user');
if(userRec.get('user_name', rec.u_created_by)){
rec.u_requestor = userRec.sys_id;
rec.update();
}
}
}
Regards
Ankur
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-24-2021 08:39 AM