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
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# GlideRecord Conditional Batch Update

## Description
This snippet updates multiple records in a ServiceNow table based on a GlideRecord encoded query.
It logs all updated records and provides a safe, controlled way to perform batch updates.

## Prerequisites
- Server-side context (Background Script, Script Include, Business Rule)
- Access to the table
- Knowledge of GlideRecord and encoded queries

## Note
- Works in Global Scope
- Server-side execution only
- Logs updated records for verification
- Can be used for maintenance, bulk updates, or automated scripts

## Usage
```javascript
// Update all active low-priority incidents to priority=2 and state=2
batchUpdate('incident', 'active=true^priority=5', {priority: 2, state: 2});
```

## Sample Output
```
Updated record: abc123
Updated record: def456
Updated record: ghi789
Batch update completed. Total records updated: 3
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* Update multiple records in a table based on an encoded query with field-level updates.
* Logs all updated records for verification.
*
* @param {string} table - Name of the table
* @param {string} encodedQuery - GlideRecord encoded query to select records
* @param {object} fieldUpdates - Key-value pairs of fields to update
*/
function batchUpdate(table, encodedQuery, fieldUpdates) {
if (!table || !encodedQuery || !fieldUpdates || typeof fieldUpdates !== 'object') {
gs.error('Table, encodedQuery, and fieldUpdates (object) are required.');
return;
}

var gr = new GlideRecord(table);
gr.addEncodedQuery(encodedQuery);
gr.query();

var count = 0;
while (gr.next()) {
for (var field in fieldUpdates) {
if (gr.isValidField(field)) {
gr.setValue(field, fieldUpdates[field]);
} else {
gs.warn('Invalid field: ' + field + ' in table ' + table);
}
}

gr.update();
gs.info('Updated record: ' + gr.getValue('sys_id'));
count++;
}

gs.info('Batch update completed. Total records updated: ' + count);
}
Loading