How to delete some number of records from a table in ServiceNow using script

Shruti08
Tera Expert

Hi All,

How to delete some number of records (ex: 5000) from a table based on a filter/query in ServiceNow using scripting?

 

Kindly help me with the steps and script.

 

Thanks in advance,

Shruti

4 REPLIES 4

Community Alums
Not applicable

Hi @Shruti08 ,

You could write a background script and delete each record :



var rec = new GlideRecord('incident');
rec.addQuery('active',false);
rec.query();
while (rec.next()) {
gs.print('Inactive incident ' + rec.number + ' deleted');
rec.deleteRecord();
}

In "System Definition --> Scripts - -Background" you will be able to run this script to delete a lot of records.

As an FYI ---> Be careful doing this. Make sure your query is correct, as deleting 8000 records can be a big oops if your delete query is not correct.

 

Do this script delete multiple records at a time?

for ex: I want to delete 100 to 150 records created before 3 months 

Does this script achieve such requirement??

Community Alums
Not applicable

Yes, it should

SNOW BOT
Tera Contributor

@Shruti08 
Please search for the "background script" in the filter navigator and use this code

var tableRef = new GlideRecord("Name_of_the_table");
tableRef.addEncodedQuery("sys_created_on<=javascript&colon;gs.beginningOfLast3Months()");// if you want to delete records created before last 3 months
tableRef.setLimit(150);// if you want to limit records upto 150
tableRef.query();
tableRef.deleteMultiple();

Please mark my answer helpful, if it works for you