Get a first look at what's coming. The Developer Passport Australia Release Preview kicks off March 12. Dive in! 

Get count of records actually updated with gliderecord.update()

Max Nowak
Kilo Sage

Hi,

 

I'm updating a lot of records in a script, and would like to now the accurate number of updates. By "accurate", I mean the number of records that actually changed.

 

Let's say I have a simple script, like this, where I - for whatever reason - want to set the Impact of all incidents to "3 - Low":

var gr = new GlideRecord('incident');
incident.query();

while(gr.next()) {
  incident.setValue('impact', '3');
  incident.update();
}

 

I know that gr.getRowCount() gives me the number of records returned from the query, which would be the number of all incidents in this case. What I need is the number of incidents actually changed, so, all Incidents where the Impact field was previously set to something other than "3".

 

I also know that ServiceNow somehow checks this and doesn't just blindly updates all records, because if I run the above script 5 times, the sys_updated_on and sys_mod_count fields are only updated once (so, only if there actually was a change).

 

Of course, I could check the fields beforehand and use my own counter variables:

var gr = new GlideRecord('incident');
incident.query();

var updateCount = 0;
var ignoreCount = 0;

while(gr.next()) {
 var impactValue = gr.getValue('impact');
  if(impactValue == '3') {
    ignoreCount++
  } else {
    incident.setValue('impact', '3');
    incident.update();
    updateCount++
  }
}

gs.info('Updated: ' + updateCount + ', ignored: ' + ignoreCount);

 

I'm wondering if there is a more elegant solution, though.

2 REPLIES 2

Not applicable

few ways to do that, but I'd use this approach:

var gr = new GlideRecord('incident');
incident.query();

var updateCount = 0;
var ignoreCount = 0;

while(gr.next()) {
 var impactValue = gr.getValue('impact');
  if(impactValue == '3') {
    ignoreCount++
  } else {
    incident.setValue('impact', '3');
    if(incident.update()){ //only if we update the record
    updateCount++;
}
  }
}

gs.info('Updated: ' + updateCount + ', ignored: ' + ignoreCount);

Jerick I
Kilo Sage

Hi Max,

 

If you can include GlideAggregate in your code, updating the record will be a lot simpler and faster. See below sample.

var updateUser = new GlideAggregate('sys_user');
updateUser.addEncodedQuery("nameLIKEabel");
updateUser.query();

    updateUser.active = true;
    updateUser.updateMultiple();

Regards,

Jeff