Skip to content

Commit 780630a

Browse files
authored
Create script.js which finds duplicates
1 parent 7352896 commit 780630a

File tree

1 file changed

+66
-0
lines changed
  • Server-Side Components/Background Scripts/Duplicate Finder

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
function findDuplicates(tableName, fieldName) {
2+
/**************************************/
3+
/*** Basic error handling on inputs ***/
4+
/**************************************/
5+
6+
// Check if table exists
7+
if (!gs.tableExists(tableName)) {
8+
// MODIFIED: Switched to string concatenation
9+
gs.info('Table "' + tableName + '" does not exist.');
10+
return;
11+
}
12+
13+
// Check if field exists
14+
var fieldGr = new GlideRecord('sys_dictionary');
15+
fieldGr.addQuery('name', tableName);
16+
fieldGr.addQuery('element', fieldName);
17+
fieldGr.query();
18+
19+
if (!fieldGr.next()) {
20+
gs.print('No field called "' + fieldName + '" on the "' + tableName + '" table.');
21+
return;
22+
}
23+
24+
/***************************************/
25+
/*********** Find duplicates ***********/
26+
/***************************************/
27+
var duplicateJson = {}; // Store the duplicate records
28+
var duplicateGroupCount = 0; // Counts the number of groups of duplicates
29+
30+
var duplicateAggregate = new GlideAggregate(tableName);
31+
duplicateAggregate.addAggregate('COUNT', fieldName);
32+
duplicateAggregate.groupBy(fieldName);
33+
duplicateAggregate.addHaving('COUNT', '>', 1); // More than 1 means it is a duplicate
34+
duplicateAggregate.addNotNullQuery(fieldName); // Ignore records where the field is empty
35+
duplicateAggregate.query();
36+
37+
while (duplicateAggregate.next()) {
38+
duplicateGroupCount++;
39+
var fieldValue = duplicateAggregate.getValue(fieldName);
40+
var countInGroup = duplicateAggregate.getAggregate('COUNT', fieldName);
41+
duplicateJson[fieldValue] = countInGroup;
42+
}
43+
44+
/***************************************/
45+
/********** Print the results **********/
46+
/***************************************/
47+
48+
// No duplicates found
49+
if (Object.keys(duplicateJson).length === 0) {
50+
gs.print('No duplicates found for field "' + fieldName + '" on table "' + tableName + '".');
51+
return;
52+
}
53+
54+
// Duplicates were found
55+
gs.print("Found " + duplicateGroupCount + " groups of duplicates:");
56+
57+
for (var key in duplicateJson) {
58+
gs.print('Value "' + key + '" has ' + duplicateJson[key] + ' occurrences.');
59+
}
60+
}
61+
62+
// Update below values to find duplicates
63+
var tableName = 'sys_user'; // ADD: Table you want for duplicates
64+
var fieldName = 'email'; // ADD: Field that you want to check for duplicates
65+
66+
findDuplicates(tableName, fieldName);

0 commit comments

Comments
 (0)