Deleting A Record
This functionality is only available to ServiceNow admins, and when deleting records proceed with caution.
If you delete records on tables that are not audited, you will never be able to retrieve this data, without getting in touch with ServiceNow Engineering support, which can be a huge pain at times.
Like anything in ServiceNow, you need to know what you’re doing, before you start executing server-side code, especially if it’s related to deleting records.
How To Delete A Record Using deleteRecord()
ServiceNow has a deleteRecord() method that is easily executable, in any server-side operation.
This cannot be done on the client-side.
To delete a record using a GlideRecord query in ServiceNow, you can use the deleteRecord()
method of the GlideRecord class.
Here is an example of how you might use this method to delete a record:
var gr = new GlideRecord('incident');
gr.addQuery('number', 'INC001');
gr.query();
if (gr.next()) {
gr.deleteRecord();
}
So what’s really going on in this code block above?
It’s really fairly simple.
This example creates a new GlideRecord for the incident
table and specifies that only records with a number
field of INC001
should be included in the results. The query()
method is then called to execute the query, and the next()
method is used to move to the first record in the results. If a record is found, the deleteRecord()
method is called to delete it.
So to delete a record, you’ll need to know it’s table, the condition, and when to delete the record.
Obviously, you should always do this in your development/test instance, before executing any code in production.
The above is just an example of how to delete a record, as your use case will likely be more complicated.
It is important to note that the deleteRecord()
method will only delete the record that is currently selected by the GlideRecord. If you want to delete multiple records, you will need to use a loop to iterate through the results and delete each record individually.
It is also worth noting that the deleteRecord()
method will only delete the record if the current user has the necessary permissions to do so. If the user does not have the necessary permissions, the method will throw an exception.
This operation is most commonly done in a Background Script by a ServiceNow admin, to clean up data.
What recommendations do you have for records that have become corrupt in some way and can’t be displayed (opening the record results in “Record not found” message) but still appear on lists, or on other tables in the hierarchy?