How to delete multiple records in table

Jalen
Tera Contributor

Hi every! My goal is to delete duplicate records in a table. The problem I am running into is that when I run my script. The script deletes both the original and the duplicate record and I cannot get it to not do that. Please help. Here is my script:

 

var tableName = 'user_authorization_table';
var field1 = 'user';
var field2 = 'user_authorization_field';
// declare an array
var dupRecords = [];
var duplicateCheck = new GlideAggregate(tableName);
duplicateCheck.addEncodedQuery("u_user.company.active=true");
duplicateCheck.addNotNullQuery(field1);
duplicateCheck.addNotNullQuery(field2);
duplicateCheck.groupBy(field1);
duplicateCheck.groupBy(field2);
duplicateCheck.addHaving('COUNT', '>', 1);
duplicateCheck.query();
while (duplicateCheck.next()) {
var jsonObj = {}; // declare a json object
jsonObj[field1] = duplicateCheck[field1].toString();
jsonObj[field2] = duplicateCheck[field2].toString();
dupRecords.push(jsonObj);
}

 
for (var i = 0; i < dupRecords.length; i++) {
var tableRec = new GlideRecord(tableName);
tableRec.addQuery(field1, dupRecords[i][field1]);
tableRec.addQuery(field2, dupRecords[i][field2]);
tableRec.query();
var count = 0;
while (tableRec.next()) {
tableRec.deleteRecord();
}
 
}
1 ACCEPTED SOLUTION

Bert_c1
Kilo Patron

Hi Jalen,

 

You can add a 'tableRec.orderBy('sys_created_on');' line to order the query results, or use 'tableRec.orderByDesc('field') before the tableRec.query(); line. And then skip the first using "TableRec.next();" before the while loop. Or change the 'while' to 'if' if you want to delete just the first result. You need to determine which of any are "duplicates". see:

 

GildeRecord API

 

And look at the two methods.

View solution in original post

3 REPLIES 3

Bert_c1
Kilo Patron

Hi Jalen,

 

You can add a 'tableRec.orderBy('sys_created_on');' line to order the query results, or use 'tableRec.orderByDesc('field') before the tableRec.query(); line. And then skip the first using "TableRec.next();" before the while loop. Or change the 'while' to 'if' if you want to delete just the first result. You need to determine which of any are "duplicates". see:

 

GildeRecord API

 

And look at the two methods.

Jalen
Tera Contributor

Thank you! The created on order by worked for me. That is the piece I was missing. 

Harish Bainsla
Kilo Patron
Kilo Patron