The Zurich release has arrived! Interested in new features and functionalities? Click here for more

Background script to update the prefix of existing records in a table

mitzaka
Mega Guru

Hi SNC,

I want to change the prefix on a table, and along with that to update all of the existing records in the table with the new prefix. The table is change_task, where the old prefix is CTASK. I want to replace it with CHGTASK.

I am trying with this background script, however I cannot seem to get them updated. Do you see anything wrong about it?

addPrefix();  

function addPrefix() {  

var x = 0;  

var pre = '';  

var num = '';  

var len = '';  

var gr = new GlideRecord('change_task');  

gr.query();  

while (gr.next()) {  

gr.setWorkflow(false); // so no business rules are run  

pre = gr.number.toString().substr(0,5); //first 5 chars of original number   to get CTASK

num = gr.number.toString().substr(5); //remaining chars of number

len = gr.number.toString().length;

if (pre == 'CTASK' && len < 11){ //11 as the chars are 12, counting 0 position

for (x = 0; x < (11-len); x++){

pre = pre + 'HG';}

gr.pre = pre + num;

gr.update();}  

}  

}  

1 ACCEPTED SOLUTION

Slava Savitsky
Giga Sage

I am not sure I understand what you are trying to do with the 'for' loop. Why not just use 'replace' method?


JavaScript String replace() Method


View solution in original post

5 REPLIES 5

Slava Savitsky
Giga Sage

I am not sure I understand what you are trying to do with the 'for' loop. Why not just use 'replace' method?


JavaScript String replace() Method


Slava Savitsky
Giga Sage

You might also want to use autoSysFields(false) to avoid changing the values of "Updated" and "Updated by" fields.


GlideRecord - ServiceNow Wiki


Slava - this were a couple of very helpful tips man, thanks.



So I did a second version of my background script using the advise and I managed to did exactly what I needed. The script I used was:



addPrefix();


function addPrefix() {


var gr = new GlideRecord('change_task');


gr.query();


while (gr.next()) {


gr.autoSysField(false); // so that the records don't have system updates


gr.setWorkflow(false); // so no business rules are run


gr.number = gr.number.replace("CTASK","CHGTASK");


gr.update();


}


}



Hi Dimitar,


I am glad to hear you got the script working. Yet an "s" seems to be missing in gr.autoSysFields(false) statement, so updates to system fields may not have been supressed. You may want to double check that.