logo

NJP

How to use GlideRecord Method to (query, select, fetch) records, Best Practices!

Import · Aug 01, 2020 · article

hello everyone how are you?

I would like to share the good practices when using glide record

If someone finds some mistake or don't agree please send your feedback;

get(Object name, Object value):

Returns the specified record in an instantiated GlideRecord object. This method accepts either one or two parameters. If only a single parameter is passed in, the method assumes it is the sys_id of the desired record.

If two parameters are passed in, the first is the name of the column within the instantiated GlideRecord to search. The second is the value to search for. If multiple records are found, use next() to access the additional records.

var grIncident = new GlideRecord('incident');
var returnValue = grIncident.get('99ebb4156fa831005be8883e6b3ee4b9');
gs.info(returnValue); // logs true or false
gs.info(grIncident.number); // logs Incident Number

When to use?

as a good practice, I always use when I have to retrieve one record and I have the key of the record.

the key could be sys_id or a unique_id from a specific field on my table.

use isEncodedQueryValid(StringQuery):

addEncodedQuery()

An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query. When the invalid query is run, the invalid part of the query condition is dropped, and the results are based on the valid part of the query, which may return all records from the table. Using an insert(), update(), deleteRecord(), or deleteMultiple() method on bad query results can result in data loss.

In the example below we have an invalid query string the field states doesn't exist, maybe the developer type states instead state without "s"

And the glideRecord retrieve all incidents with priority 5 and ignore the state filter, because the field states do not exist, so be careful when using the addEncodedQuery or use the isEncodedQueryValid()

Example: (state 1 = New)

image

info: You can set the glide.invalid_query.returns_no_rows system property to true to have queries with invalid encoded queries return no records.

Let's use isEncodedQueryValid image

EncodedQueryValid() returns true or false and don't retrieve any records if the encoded query is not valid;

So I started to use this method instead of addEncodedQuery this help me create more trustful and reliability scripts.

image

image

Codes, snippets you find on my repository

Follow me on my Github repository: https://github.com/raphaelcrv/servicenow-snippets/blob/master/GlideRecord%20Query%20Cheat%20Sheet.md

View original source

https://www.servicenow.com/community/developer-articles/how-to-use-gliderecord-method-to-query-select-fetch-records-best/ta-p/2321811