You are currently viewing GlideRecord getValue() vs addQuery()

GlideRecord getValue() vs addQuery()

In ServiceNow, GlideRecord is a powerful API used for querying, updating, and manipulating records in a database table.

The GlideRecord object has two methods, getValue() and addQuery(), each of which has a distinct function.

getValue() method

The value of a field on the current record or a related record may be obtained using the getValue() function.

You may use getValue(“short_description”) to get the value of the short description field on an incident record, for instance, if you have a GlideRecord object that represents an incident record.

Example

Let’s say you want to retrieve the short description of the incident record with sys_id = 123456. You can use the following code:

var gr = new GlideRecord('incident');
gr.get('sys_id', '123456');
var shortDesc = gr.getValue('short_description');
gs.info('Short Description: ' + shortDesc);

This code creates a new GlideRecord object for the ‘incident’ table and retrieves the incident record with sys_id = 123456 using the get() method. Then it retrieves the value of the short description field using the getValue() method and stores it in the shortDesc variable. Finally, it logs the short description to the system log using the gs.info() method.

addQuery() method

A query condition may be added to the GlideRecord object using the addQuery() method. The field to query on and the value to query for are the two inputs for this method.

For instance, you may use addQuery(‘short_description’, ‘CONTAINS’, ‘network’) to search for any incident records that include the term “network” in the short description.

Example

Let’s say you want to retrieve all incident records with a priority of 1 and a state of ‘Resolved’. You can use the following code:

var gr = new GlideRecord('incident');
gr.addQuery('priority', '1');
gr.addQuery('state', 'Resolved');
gr.query();
while (gr.next()) {
  gs.info('Incident Number: ' + gr.number + ', Priority: ' + gr.priority + ', State: ' + gr.state);
}

This code creates a new GlideRecord object for the ‘incident’ table and adds two query conditions using the addQuery() method: priority = 1 and state = ‘Resolved’. Then it runs the query using the query() method and loops through the result set using the next() method. For each record in the result set, it logs the incident number, priority, and state to the system log using the gs.info() method.

In summary, the GlideRecord object’s getValue() method retrieves the value of a particular field, and addQuery() adds a query condition to the object to select the records that will be returned.

Leave a Reply