diff --git a/Core ServiceNow APIs/GlideRecord/Conditional Batch Update/README.md b/Core ServiceNow APIs/GlideRecord/Conditional Batch Update/README.md new file mode 100644 index 0000000000..7a4d900643 --- /dev/null +++ b/Core ServiceNow APIs/GlideRecord/Conditional Batch Update/README.md @@ -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 +``` \ No newline at end of file diff --git a/Core ServiceNow APIs/GlideRecord/Conditional Batch Update/batchUpdate.js b/Core ServiceNow APIs/GlideRecord/Conditional Batch Update/batchUpdate.js new file mode 100644 index 0000000000..4be2bba0d7 --- /dev/null +++ b/Core ServiceNow APIs/GlideRecord/Conditional Batch Update/batchUpdate.js @@ -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); +}