How to delete some number of records from a table in ServiceNow using script
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-12-2023 06:36 AM
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-12-2023 06:40 AM
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-12-2023 06:44 AM
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??
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-12-2023 06:45 AM
Yes, it should
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-12-2023 06:52 AM
@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: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