Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions Core ServiceNow APIs/GlideRecord/Compare_2_records/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Compare Two Records Using GlideRecord (Global Scope)

This snippet compares two records from the same table in ServiceNow field-by-field using the **GlideRecord API**.
It’s useful for debugging, verifying data after imports, or checking differences between two similar records.

---

## Working
The script:
1. Retrieves two records using their `sys_id`.
2. Includes or Excludes the system fields.
2. Iterates over all fields in the record.
3. Logs any fields where the values differ.

---

## Scope
This script is designed to run in the Global scope.
If used in a scoped application, ensure that the target table is accessible from that scope (cross-scope access must be allowed).

## Usage
Run this script in a **Background Script** or **Fix Script**:

```js
compareRecords('incident', 'sys_id_1_here', 'sys_id_2_here', false);
```
---
## Example Output
```js
short_description: "Printer not working" vs "Printer offline"
state: "In Progress" vs "Resolved"
priority: "2" vs "3"
Comparison complete.
```

Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* Compare two records in a ServiceNow table field-by-field.
* Logs all field differences between the two records, including display values.
*
* Parameters:
* @param {string} table - Table name
* @param {string} sys_id1 - sys_id of first record
* @param {string} sys_id2 - sys_id of second record
* @param {boolean} includeSystemFields - true to compare system fields, false to skip them
*
* Usage:
* compareRecords('incident', 'sys_id_1_here', 'sys_id_2_here', true/false);
*/

function compareRecords(table, sys_id1, sys_id2, includeSystemFields) {
var rec1 = new GlideRecord(table);
var rec2 = new GlideRecord(table);

if (!rec1.get(sys_id1) || !rec2.get(sys_id2)) {
gs.error('One or both sys_ids are invalid for table: ' + table);
return;
}

var fields = rec1.getFields();
gs.info('Comparing records in table: ' + table);

for (var i = 0; i < fields.size(); i++) {
var field = fields.get(i);
var fieldName = field.getName();

if( !includeSystemFields && fieldName.startsWith('sys_') ) {
continue;
}

var val1 = rec1.getValue(fieldName);
var val2 = rec2.getValue(fieldName);

var disp1 = rec1.getDisplayValue(fieldName);
var disp2 = rec2.getDisplayValue(fieldName);

if (val1 != val2) {
gs.info(
fieldName + ': Backend -> "' + val1 + '" vs "' + val2 + '", ' +
'Display -> "' + disp1 + '" vs "' + disp2 + '"'
);
}
}

gs.info('Comparison complete.');
}

// Example call
compareRecords('incident', 'sys_id_1_here', 'sys_id_2_here', false);
Loading