File tree Expand file tree Collapse file tree 2 files changed +65
-0
lines changed
Core ServiceNow APIs/GlideRecord/Conditional Batch Update Expand file tree Collapse file tree 2 files changed +65
-0
lines changed Original file line number Diff line number Diff line change 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+ ```
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments