how to delete the duplicate records in m2m tables

NithyadeviH9387
Mega Contributor

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.

1 REPLY 1

Pratiksha
Mega Sage
Mega Sage

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