script for deleting duplicate records

sbhayani
Tera Contributor

Hello Experts,

I want to delete the duplicate records from router interface table, I scripted following code, but not sure, why isnt it working,

Can you help please?

var dup = new GlideAggregate('dscy_router_interface');
 dup.addAggregate('COUNT', 'mac_address');
 dup.addHaving('COUNT', 'mac_address', '>', '1'); //returns only records having more than one active instance of dupeField (duplicates)
 dup.query();
 var listOfDupes = []; //build array to push the results into
 while (dup.next()) {
  listOfDupes.push(dup.getValue('mac_address')); //Push the value of the dupe field to the array
 }
var dup1 = new GlideRecord('dscy_router_interface');
dup1.addQuery('sys_id','IN',listofDupes.toString());
dup1.orderByDesc('sys_created_on');
dup1.query();
dup1.next();
while(dup1.next())
 dup1.deleteRecord();

1 ACCEPTED SOLUTION

Shishir Srivast
Mega Sage

May be you can try with below script:

 

var dup = new GlideAggregate('dscy_router_interface');
dup.groupBy('mac_address');
dup.query();
while(dup.next()) {
	var dup1 = new GlideRecord('dscy_router_interface');
	dup1.addQuery('mac_address', dup.mac_address);
	dup1.query();
	dup1.next();
	while(dup1.next())
		dup1.deleteRecord();
}

View solution in original post

9 REPLIES 9

Shishir Srivast
Mega Sage

May be you can try with below script:

 

var dup = new GlideAggregate('dscy_router_interface');
dup.groupBy('mac_address');
dup.query();
while(dup.next()) {
	var dup1 = new GlideRecord('dscy_router_interface');
	dup1.addQuery('mac_address', dup.mac_address);
	dup1.query();
	dup1.next();
	while(dup1.next())
		dup1.deleteRecord();
}

Thanks! this worked really well.

Thank you Shishir

 

I have the same issue and It worked perfectly. 🙂

Hi Shishir, If I needed to check on 2 fields how would I need to change the code?

Example

John    Doe

John    Johnson

John     Doe

Remove the second John Doe.