The Now Platform® Washington DC release is live. Watch now!

Help
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

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

14 REPLIES 14

kenappell
Kilo Guru

Maybe try the deleteMultiple() function?


GlideRecord - ServiceNow Wiki


Hi Ken,



You are right, I should have added an extra line in, as I am testing I am just trying to delete 1 line to see if it works. After I have a success I will be changing the last line to deleteMultiple().



At this stage it doesn't delete any records though.


santoshsahoonis
Kilo Guru

Hello Lucien,



I think you are missing "" in the query.



change line 3 to:


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



So the full script would be:



P.S:You can use deleteMultiple instead of the while loop



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();  


gr.deleteMultiple();  



Pradeep Sharma
ServiceNow Employee
ServiceNow Employee

Hi Lucien,



Breakdown is a reference field and it expects sys_id value. Can you replace breakdown with breakdown.name


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