How To Use While Loops In A GlideRecord Query

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. …

while loop next example

Buy The "ServiceNow Developer's Manual" Now

We've packed over a decade of ServiceNow Development advice, into a single e-book.

Buy It Now
Stripe Climate Badge

The Snowball will contribute 5% of your purchase to remove CO₂ from the atmosphere.

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:

  1. We initiate a new GlideRecord query on the incident table.
  2. We add a query to filter incidents that are in the ‘New’ state.
  3. The query() method is then called to execute our query.
  4. We use the while loop combined with the next() method to iterate over each record that matches our query.
  5. 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:

  1. We start by initiating a GlideRecord query on the incident table.
  2. We filter the incidents that are in an ‘Open’ state and have a ‘Low’ priority.
  3. After executing the query, we use the while loop and next() method to iterate through each matching incident.
  4. 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:

  1. Here, we’re working with the sys_user table, which contains records of ServiceNow users.
  2. We’re interested in users who are currently active (active field set to true) and belong to the ‘IT’ department.
  3. Post-query, the while loop iterates over each user that fits our criteria.
  4. 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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.



What Do You Think About This Article?

5 1 vote
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] Go here for more information on how to use while loops in ServiceNow Scripting. […]

Product Image

Richard just purchased A ServiceNow Developer’s Manual 16 Hours ago from Oakland CA.

Buy Now
1
0
Would love your thoughts, please comment.x
()
x