Script will only update one record

dcutrano
Giga Contributor

I'm trying to run a mass update of approximately 1700 records but my script is only processing one record at a time.   I've checked the query by commenting out the last two lines of code and it definitely is a valid query.   I'm using while loop, I can figure out why this is only processing one record per run.

var queryString = "incident_stateIN7,9^u_inc_resolved_datetimeISEMPTY^opened_atBETWEENjavascript:gs.dateGenerate('2015-02-16','00:00:42')@javascript:gs.daysAgoEnd^ORsys_updated_onBETWEENjavascript:gs.dateGenerate('2015-02-16','00:00:42')@javascript:gs.daysAgoEnd";

var target = new GlideRecord('incident');

target.addEncodedQuery(queryString);

target.query();

while (target.next()) {

  gs.log('incident:' + target.number);

  target.u_inc_resolved_datetime = target.u_completed_date;

  target.update();

}

1 ACCEPTED SOLUTION

manikorada
ServiceNow Employee
ServiceNow Employee

David,



If you are running the script from a scheduled job or backend script   and if you do the above way all your variables are global and therefore if any other business rule or any script running at that time uses the variable "target" it will wipe yours out.


And, if you are running from Scheduled Job, then the script needs be always kept in a   function.


View solution in original post

4 REPLIES 4

manikorada
ServiceNow Employee
ServiceNow Employee

David,



If you are running the above script from a scheduled job or a scripts background. Its always good to do scoping on your code.


So, I would do something like:



doUpdate();



function doUpdate()


{


var queryString = "incident_stateIN7,9^u_inc_resolved_datetimeISEMPTY^opened_atBETWEENjavascript:gs.dateGenerate('2015-02-16','00:00:42')@javascript:gs.daysAgoEnd^ORsys_updated_onBETWEENjavascript:gs.dateGenerate('2015-02-16','00:00:42')@javascript:gs.daysAgoEnd";


var target = new GlideRecord('incident');


target.addEncodedQuery(queryString);


target.query();



while (target.next()) {


  gs.log('incident:' + target.number);


  target.u_inc_resolved_datetime = target.u_completed_date;


  target.update();


}


}


Mani....Thanks for the prompt reply.   What does creating a function do.   Can you please explain a little?


manikorada
ServiceNow Employee
ServiceNow Employee

David,



If you are running the script from a scheduled job or backend script   and if you do the above way all your variables are global and therefore if any other business rule or any script running at that time uses the variable "target" it will wipe yours out.


And, if you are running from Scheduled Job, then the script needs be always kept in a   function.


I get it now.   Thanks for your help.   BTW...it worked like a charm