how to delete the duplicate records in m2m tables
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-26-2025 09:34 AM
Can anyone say, how to delete the duplicate records in m2m tables through script.Is there any alternate way to delete the duplicates without code.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-26-2025 09:51 AM - edited 03-26-2025 09:52 AM
var tableName = "your_m2m_table"; // Replace with the actual M2M table name
var grAgg = new GlideAggregate(tableName);
grAgg.addAggregate('COUNT');
grAgg.groupBy('tableA'); // Adjust based on your table structure
grAgg.groupBy('tableB');
grAgg.query();
while (grAgg.next()) {
var count = grAgg.getAggregate('COUNT');
if (count > 1) {
var gr = new GlideRecord(tableName);
gr.addQuery('tableA', grAgg.getValue('tableA'));
gr.addQuery('tableB', grAgg.getValue('tableB'));
gr.orderBy('sys_created_on'); // Keeping the oldest record
gr.query();
var firstRecord = true;
while (gr.next()) {
if (firstRecord) {
firstRecord = false; // Skip the first record
} else {
gs.info("Deleting duplicate: " + gr.getUniqueValue());
gr.deleteRecord();
}
}
}
}
FYI just asked chat gpt 🙂
Regards,
Pratiksha