Skip to content

Commit e77c7ec

Browse files
authored
Add Conditional Batch Update (#2579)
1 parent 1ba7479 commit e77c7ec

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# GlideRecord Conditional Batch Update
2+
3+
## Description
4+
This snippet updates multiple records in a ServiceNow table based on a GlideRecord encoded query.
5+
It logs all updated records and provides a safe, controlled way to perform batch updates.
6+
7+
## Prerequisites
8+
- Server-side context (Background Script, Script Include, Business Rule)
9+
- Access to the table
10+
- Knowledge of GlideRecord and encoded queries
11+
12+
## Note
13+
- Works in Global Scope
14+
- Server-side execution only
15+
- Logs updated records for verification
16+
- Can be used for maintenance, bulk updates, or automated scripts
17+
18+
## Usage
19+
```javascript
20+
// Update all active low-priority incidents to priority=2 and state=2
21+
batchUpdate('incident', 'active=true^priority=5', {priority: 2, state: 2});
22+
```
23+
24+
## Sample Output
25+
```
26+
Updated record: abc123
27+
Updated record: def456
28+
Updated record: ghi789
29+
Batch update completed. Total records updated: 3
30+
```
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Update multiple records in a table based on an encoded query with field-level updates.
3+
* Logs all updated records for verification.
4+
*
5+
* @param {string} table - Name of the table
6+
* @param {string} encodedQuery - GlideRecord encoded query to select records
7+
* @param {object} fieldUpdates - Key-value pairs of fields to update
8+
*/
9+
function batchUpdate(table, encodedQuery, fieldUpdates) {
10+
if (!table || !encodedQuery || !fieldUpdates || typeof fieldUpdates !== 'object') {
11+
gs.error('Table, encodedQuery, and fieldUpdates (object) are required.');
12+
return;
13+
}
14+
15+
var gr = new GlideRecord(table);
16+
gr.addEncodedQuery(encodedQuery);
17+
gr.query();
18+
19+
var count = 0;
20+
while (gr.next()) {
21+
for (var field in fieldUpdates) {
22+
if (gr.isValidField(field)) {
23+
gr.setValue(field, fieldUpdates[field]);
24+
} else {
25+
gs.warn('Invalid field: ' + field + ' in table ' + table);
26+
}
27+
}
28+
29+
gr.update();
30+
gs.info('Updated record: ' + gr.getValue('sys_id'));
31+
count++;
32+
}
33+
34+
gs.info('Batch update completed. Total records updated: ' + count);
35+
}

0 commit comments

Comments
 (0)