How to delete duplicates based on 2 fields

Dead Blade
Kilo Guru

Hi,

So I've scrubbed through the forums and found many scripts to delete duplicate records, but they are all based on 1 field.  Some of which are using GlideAggregate.  So I need a script to delete records based on several field criteria.  Example

Field 1     Field 2

John        Smith

John        Doe

John        Smith

John        Johnson

Delete the Duplicate John Smiths. 

I will be using this script as a fix script running on a schedule as maintenance for an m2ms table.  The fields are reference fields if that matters.

1 ACCEPTED SOLUTION

Blade,

Try using the below code:

 

var optionsObj=JSON.parse(FindDuplicateRecords());
    
    for (var i = 0; i < optionsObj.length; i++) {
        
        var gr=new GlideRecord('u_m2m_authorize_servers');
        gr.addQuery('u_group',optionsObj[i].group);
        gr.addQuery('u_server',optionsObj[i].server);
        gr.query();
        var deleteCount = gr.getRowCount();
        while(gr.next()) {

         if(deleteCount!=1)

        {
            gr.deleteRecord();
            deleteCount--;
            gs.info('Record: ' + gr.optionsObj[i].group + gr.optionsObj[i].server + ' Deleted');
            gs.info('Records Deleted = ' + deleteCount);

         }
        }
    }

If the solution is helpful please mark it as helpful

View solution in original post

22 REPLIES 22

This is extremely helpful and I do appreciate it.  Still a little more work left.  That is progress, but now it finds the duplicates and deletes the duplicate + the last remaining record of that duplicate.  So there is no record left. 

Blade,

Try using the below code:

 

var optionsObj=JSON.parse(FindDuplicateRecords());
    
    for (var i = 0; i < optionsObj.length; i++) {
        
        var gr=new GlideRecord('u_m2m_authorize_servers');
        gr.addQuery('u_group',optionsObj[i].group);
        gr.addQuery('u_server',optionsObj[i].server);
        gr.query();
        var deleteCount = gr.getRowCount();
        while(gr.next()) {

         if(deleteCount!=1)

        {
            gr.deleteRecord();
            deleteCount--;
            gs.info('Record: ' + gr.optionsObj[i].group + gr.optionsObj[i].server + ' Deleted');
            gs.info('Records Deleted = ' + deleteCount);

         }
        }
    }

If the solution is helpful please mark it as helpful

Team work.  Awesome thank you both aashishdasari and dvp!