Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Delete multiple records using background scripts

Lucien1
Giga Expert

Hi all,

I have modified this script I found to try delete multiple records but so far it fails.

I am going to be using the scripts background function as it is just a 1 time event. The records are before the 1st of April so I added an encoded query. Can anyone see where I am going wrong as I can't sit and delete all these records manually.

var gr = new GlideRecord('pa_scores');

gr.addQuery('breakdown','=', 'Model Category');

gr.addEncocdedQuery(sys_created_on<=javascript:gs.dateGenerate('2016-03-31','23:59:59'));

gr.query();

while (gr.next()) {

    //Delete each record in the query result set

  gr.deleteRecord();

}

Thanks,

Lucien

1 ACCEPTED SOLUTION

Lucien1
Giga Expert

Thanks all for your help and with a bit of changes with your guidance I got it working. Below is what I have used.



var gr = new GlideRecord('pa_scores');


gr.addQuery('breakdown.name','=', 'Model Category'); // Pradeep Sharma update


gr.addEncodedQuery('sys_created_on<=' + gs.dateGenerate('2016-03-31','23:59:59')); // Chuck Tomasi update


gr.query();


while (gr.next()) {


  gr.deleteMultiple(); // Ken and Santosh update


}




It still took time to delete these records (Dev instance 1st) but now that I know it works I can do this in production.


View solution in original post

15 REPLIES 15

j_15
Tera Expert

The accepted solution is sub-optimal. There is no need to put deleteMultiple() in a loop. It will iterate over the records returned within the GlideRecord object by itself.

 

var gr = new GlideRecord('pa_scores');
gr.addQuery('breakdown.name','=', 'Model Category'); // Pradeep Sharma update
gr.addEncodedQuery('sys_created_on<=' + gs.dateGenerate('2016-03-31','23:59:59')); // Chuck Tomasi update
gr.query();
gr.deleteMultiple();