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