Properly Using While Loops In A GlideRecord Query
ServiceNow’s GlideRecord is a powerful tool that every developer and admin should have in their toolkit.
With it, querying and manipulating data within ServiceNow becomes a breeze. However, when combined with loops, especially while
loops, the power multiplies but so do the risks.
In this post, we’ll dissect the proper usage of while
loops with GlideRecord queries.
Introduction to GlideRecord with While Loops
GlideRecord is the server-side scripting API provided by ServiceNow. It enables developers to work with tables and records seamlessly. Now, when we marry this capability with while
loops, we can iterate over multiple records, making bulk changes, data extracts, or other repetitive tasks more efficient.
However, without the proper precautions, this pairing can lead to unintended behaviors, performance issues, or even infinite loops. Thus, understanding the right way to use them is paramount.
Practical Implementation with Scripting
Let’s illustrate the concept with an example. Suppose you want to retrieve all incidents in the ‘New’ state and log their number and short description:
Example 1: Logging New Incidents
var gr = new GlideRecord('incident');
gr.addQuery('state', '1'); // 1 corresponds to the 'New' state in the Incident table
gr.query();
while (gr.next()) {
gs.info('Incident number: ' + gr.number + ', Description: ' + gr.short_description);
}
Commentary on the Code:
- We initiate a new GlideRecord query on the
incident
table. - We add a query to filter incidents that are in the ‘New’ state.
- The
query()
method is then called to execute our query. - We use the
while
loop combined with thenext()
method to iterate over each record that matches our query. - Inside the loop, we log the number and short description of each incident.
Example 2: Updating Priority of Open Incidents
var gr = new GlideRecord('incident');
// Query for incidents in 'Open' state with a 'Low' priority
gr.addQuery('state', '2'); // 2 corresponds to 'Open'
gr.addQuery('priority', '4'); // 4 corresponds to 'Low'
gr.query();
while (gr.next()) {
gr.priority = '3'; // Setting the priority to 'Moderate'
gr.update();
}
Commentary:
- We start by initiating a GlideRecord query on the
incident
table. - We filter the incidents that are in an ‘Open’ state and have a ‘Low’ priority.
- After executing the query, we use the
while
loop andnext()
method to iterate through each matching incident. - Inside the loop, for every matching incident, we change its priority from ‘Low’ to ‘Moderate’ and then save the change with the
update()
method.
Example 3: Logging Active Users from a Specific Department
var gr = new GlideRecord('sys_user');
// Query for active users from the 'IT' department
gr.addQuery('active', true);
gr.addQuery('department.name', 'IT');
gr.query();
while (gr.next()) {
gs.info('User: ' + gr.name + ', Email: ' + gr.email);
}
Commentary:
- Here, we’re working with the
sys_user
table, which contains records of ServiceNow users. - We’re interested in users who are currently active (
active
field set totrue
) and belong to the ‘IT’ department. - Post-query, the
while
loop iterates over each user that fits our criteria. - Within the loop, we log the name and email of each such user, providing us with a quick report of active IT department users.
In both examples, the combination of GlideRecord queries with while
loops allows us to effectively process multiple records based on certain criteria. Whether updating records or logging specific details, this technique is invaluable for ServiceNow developers, aiding in various administrative and development tasks.
Best Practices and Considerations
- Limit the Records: Always be cautious about the number of records your query might return. If possible, use
setLimit()
to prevent returning more records than needed. - Avoid Infinite Loops: Ensure there’s a termination condition. The
next()
method in GlideRecord naturally ensures that the loop exits once all records are processed. However, always be wary of conditions that might keep the loop running indefinitely. - Be Mindful of Performance: If you’re dealing with a large number of records, remember that each operation within the loop will multiply. This can lead to performance issues. Consider other methods like scheduled jobs or data transforms for very large operations.
- Test in Sub-Production: Always test scripts, especially those with potential broad impacts, in a sub-production environment first to ensure they behave as expected.
- Transaction Control: Be aware of ServiceNow’s transaction boundaries. If your loop involves updates, you might want to use
_update()
sparingly and consider using batch updates.
Concluding Thoughts On Loops
When wielded correctly, the combination of GlideRecord and while
loops in ServiceNow can be incredibly potent.
They allow developers to craft efficient, powerful scripts that can transform data operations.
However, with great power comes great responsibility. Always approach such scripts with caution, respecting the guidelines and best practices to ensure you harness their capabilities without compromising the health and performance of your instance.
As always, continuous learning and practice are the keys to mastering these tools.
[…] Go here for more information on how to use while loops in ServiceNow Scripting. […]