The GlideRecord class is the way to interact with the ServiceNow database from a script.
GlideRecord interactions start with a database query.
The generalized strategy is:
// 1. Create an object to store rows from a table
var myObj = new GlideRecord('table_name');
// 2. Build query
myObj.addQuery('field_name','operator','value');
myObj.addQuery('field_name','operator','value');
// 3. Execute query
myObj.query();
// 4. Process returned records
while(myObj.next()){
//Logic you want to execute.
//Use myObj.field_name to reference record fields
}
There is a client-side GlideRecord API for global applications.
The client-side GlideRecord API cannot be used in scoped applications.
The addQuery operators are:
In some scripts you will see only two arguments: field name and value.
Queries with no query conditions return all records from a table.
An incorrectly constructed encoded query, such as including an invalid field name, produces an invalid query.
You can set the
glide.invalid_query.returns_no_rowssystem property totrueto have queries with invalid encoded queries return no records.
- In some cases, the query may still return records in API results even when
glide.invalid_query.returns_no_rowsis set totrue.
next() method and a while loop iterates through all returned records to process script logic:// iterate through all records in the GlideRecord and set the Priority field value to 4 (low priority).
// update the record in the database
while(myObj.next()){
myObj.priority = 4;
myObj.update();
}
next() method and an if processes only the first record returned.// Set the Priority field value to 4 (low priority) for the first record in the GlideRecord
// update the record in the database
if(myObj.next()){
myObj.priority = 4;
myObj.update();
}
updateMultiple() method to update all records in a GlideRecord.updateMultiple() method, set field values with the the setValue() method rather than direct assignment.// When using updateMultiple(), use the setValue() method.
// Using myObj.priority = 4 may return unexpected results.
myObj.setValue('priority',4);
myObj.updateMultiple();
getRowCount().getRowCount() method on a production instance as there could be a negative performance impact on the database.// If you need to know the row count for a query on a production instance do this
var count = new GlideAggregate('x_snc_needit_needit');
count.addAggregate('COUNT');
count.query();
var recs = 0;
if (count.next()){
recs = count.getAggregate('COUNT');
}
gs.info("Returned number of rows = " +recs);
// Do not do this on a production instance.
var myObj = new GlideRecord('x_snc_needit_needit');
myObj.query();
gs.info("Returned record count = " + myObj.getRowCount());
var myObj = new GlideRecord("x_snc_needit_needit");
myObj.addEncodedQuery('<your_encoded_query>');
myObj.query();
while(myObj.next()){
// Logic you want to execute for the GlideRecord records
}
<table_name>.list in the Filter field.addEncodedQuery() method.Be sure to enclose the encoded query in “” or ‘’.
var myObj = new GlideRecord("x_snc_needit_needit");
myObj.addEncodedQuery("u_when_neededBETWEENjavascript:gs.daysAgoStart(0)@javascript:gs.quartersAgoEnd(1)^active=true^state=14^ORstate=16");
myObj.query();
while(myObj.next()){
// Insert logic you want to execute for the GlideRecord records
}
In most cases, don’t use dot-walking to get values from a record.
getValue()getDisplayValue()If dot-walking through a GlideElement object is necessary, use the toString() method to retrieve values.
var mgr = current.caller_id.manager.toString();
Creates an instance of the GlideRecord class for the specified table.
var now_GR = new GlideRecord('incident');
var inc = new GlideRecord('incident');
inc.addActiveQuery();
inc.query();
var inc = new GlideRecord('incident');
inc.addInactiveQuery();
inc.query();
null.var target = new GlideRecord('incident');
target.addNotNullQuery('short_description');
target.query(); // Issue the query to the database to get all records
while (target.next()) {
// add code here to process the incident record
}
null.var target = new GlideRecord('incident');
target.addNullQuery('short_description');
target.query(); // Issue the query to the database to get all records
while (target.next()) {
// add code here to process the incident record
}
It can be called with only two parameters, table field and comparison value, such as myObj.addQuery('category','Hardware');.
var rec = new GlideRecord('incident');
rec.addQuery('active',true);
rec.addQuery('sys_created_on', ">", "2010-01-19 04:05:00");
rec.query();
while (rec.next()) {
rec.active = false;
gs.print('Active incident ' + rec.number + ' closed');
rec.update();
}
var que = new GlideRecord('incident');
que.addQuery('number','IN','INC00001,INC00002');
que.query();
while(que.next()) {
//do something....
}
GlideQueryCondition API provides additional AND or OR conditions that can be added to the current condition, allowing you to build complex queries.addCondition(), an implied AND is added.var now_GR = new GlideRecord('incident');
var qc = now_GR.addQuery('category', 'Hardware');
qc.addCondition('category', 'Network');
now_GR.addQuery('number','INC0000003');
now_GR.next();
now_GR.number;
gs.info(now_GR.getEncodedQuery());
var now_GR = new GlideRecord('incident');
var qc = now_GR.addQuery('category', 'Hardware');
qc.addOrCondition('category', 'Network');
now_GR.addQuery('number','INC0000003');
now_GR.next();
now_GR.number;
gs.info(now_GR.getEncodedQuery());
(state < 3 OR state > 5) AND (priority = 1 OR priority = 5) use code similar to the following:var myObj = new GlideRecord('incident');
var q1 = myObj.addQuery('state', '<', 3);
q1.addOrCondition('state', '>', 5);
var q2 = myObj.addQuery('priority', 1);
q2.addOrCondition('priority', 5);
myObj.query();
var queryString = "priority=1^ORpriority=2";
var now_GR = new GlideRecord('incident');
now_GR.addEncodedQuery(queryString);
now_GR.query();
while (now_GR.next()) {
gs.addInfoMessage(now_GR.number);
}
function createAcl(table, role) {
gs.print("Checking security on table " + table);
var now_GR = new GlideRecord("sys_security_acl");
now_GR.addQuery("name", table);
now_GR.addQuery("operation", "read");
now_GR.query();
var encQuery = now_GR.getEncodedQuery();
if (now_GR.next()) {
// existing acl found so use it
createAclRole(now_GR.sys_id.toString(), role);
return;
} else {
now_GR.initialize();
now_GR.applyEncodedQuery(encQuery);
var acl = now_GR.insert();
gs.print("Added read access control on " + table);
createAclRole(acl, role);
}
}
var now_GR = new GlideRecord("sys_security_acl");
now_GR.addQuery("name", table);
now_GR.addQuery("operation", "read");
now_GR.query();
var encQuery = now_GR.getEncodedQuery();
addExtraField() method allows you to query dot-walked fields in a single database request, rather than perform multiple queries per dot-walked element in a form or script (which requires multiple round trips to the database).var gliderecord = new GlideRecord("incident");
gliderecord.addQuery("number", "INC0041457");
gliderecord.addExtraField("cmdb_ci.location.contact.name");
gliderecord.query();
gliderecord.next();
gs.print(gliderecord.cmdb_ci.location.contact.name);
Note: The
addExtraField()method does not impact output results; the output is always the same regardless if you use this method in your script.
gs.print(gr.cmdb_ci.location.contact.name) with addExtraField() is same as without using addExtraField().addExtraField() method optimizes the querying of the dot-walked fields.For example, find all the users that are in the database group (users via sys_user_grmember table). - Another example would be find all problems that have an assigned incident (problems via the incident.problem_id relationship).
var prob = new GlideRecord('problem');
prob.addJoinQuery('incident');
prob.query();
sys_id, the primary field.var now_GR = new GlideRecord('problem');
now_GR.addJoinQuery('incident', 'opened_by');
now_GR.query();
var now_GR = new GlideRecord('problem');
now_GR.addJoinQuery('incident', 'opened_by', 'caller_id');
now_GR.query();
incident caller_id field value matches that of the problem opened_by field.Provides atomic add and subtract operations on a specified number field at the database level for the current GlideRecord object.
For example, when the following code is executed, the value of the u_count field in the database is 2.
gs.print(now_now_GR.u_count); // "1"
now_GR.u_count += 1;
now_GR.update();
now_GR.get(now_now_GR.sys_id);
gs.print(now_now_GR.u_count); // "2"
gs.print(now_now_GR.u_count); // "1"
now_GR.addValue("u_count", 1);
now_GR.update();
now_GR.get(now_GR); // The record must be reloaded from the database to observe the result
gs.print(now_now_GR.u_count); // "3", if executed concurrently with another user
Note: If setValue() is called for the specified field prior to calling addValue(), the addValue() method is not processed and an error message is logged.
var rec1 = new GlideRecord("incident");
rec1.initialize();
rec1.applyTemplate("my_incident_template");
rec1.insert();
Warning: Use caution if you use this method.
- When you use this method the sys_mod_count field will not be incremented, and other sys_ fields will not be updated.
- This can break functionality including, but not limited to, the Activity Formatter, History Sets, Notifications, and Metrics.
var inc = new GlideRecord('incident');
// Change all Open(1) incidents to Active(2)
inc.addQuery('state', 1);
inc.query();
while (inc.next()) {
inc.autoSysFields(false); // Do not update sys_updated_by, sys_updated_on, sys_mod_count, sys_created_by, and sys_created_on
inc.setWorkflow(false); // Do not run any other business rules
inc.setValue('state', 2);
inc.update();
}
var now_GR = new GlideRecord('benefit_plan');
return now_GR.canCreate();
var now_GR = new GlideRecord('benefit_plan');
return now_GR.canRead();
var now_GR = new GlideRecord('benefit_plan');
return now_GR.canWrite();
var now_GR = new GlideRecord("incident");
now_GR.query();
now_GR.next();
if (now_GR.changes()) {
gs.print("The incident record reported changes right after being read");
} else {
gs.print("The incident record has not changed");
}
var rec = new GlideRecord('incident');
rec.addQuery('active',false);
rec.query();
while (rec.next()) {
gs.info('Inactive incident ' + rec.number + ' deleted');
rec.deleteRecord();
}
var now_GR = new GlideRecord('incident');
now_GR.addQuery('active','false');
now_GR.query();
now_GR.deleteMultiple();
var now_GR = new GlideRecord("incident");
now_GR.query();
var shortDescription = "Critical";
if (now_GR.find("short_description", shortDescription)) {
gs.print("An incident with the specified field value was found");
var recordID = now_GR.getValue("sys_id");
gs.print("Found in the following record: " + recordID);
} else {
gs.print("An incident with the specified field value was not found");
}
var grIncident = new GlideRecord('incident');
var returnValue = grIncident.get('99ebb4156fa831005be8883e6b3ee4b9');
gs.info(returnValue); // logs true or false
gs.info(grIncident.number); // logs Incident Number
var grIncident = new GlideRecord('incident');
var returnValue = grIncident.get('caller_id.name','Sylivia Wayland');
gs.info(returnValue); // logs true or false
gs.info(grIncident.number); // logs Incident Number
var now_GR = new GlideRecord('sys_user');
now_GR.query("user_name","admin");
if (now_GR.next()) {
gs.print("we got one");
gs.print(now_GR.location.getAttribute("tree_picker"));
}
// Display the incident table label
var now_GR = new GlideRecord("incident");
var value = now_GR.getClassDisplayValue();
gs.info("The table label is " + value + ".");
var now_GR = new GlideRecord('incident');
now_GR.get('sys_id','<sys_id>');
gs.info(now_GR.getDisplayValue());
For this method to work, a display value must have been set on the associated table.
var escapeValue = now_GR.getEscapedDisplayValue();
gs.print("Escaped name: " + escapeValue);
// Get a single incident record
var grINC = new GlideRecord('incident');
grINC.query();
grINC.next();
gs.print('Using ' + grINC.getValue('number'));
gs.print('');
// getFields() returns a Java ArrayList
var fields = grINC.getFields();
&sysparm_stack=[tablename]_list.do? sysparm_query=active=true.var classname = current.getRecordClassName();
var now_GR = new GlideRecord('incident');
var c = now_GR.getRelatedLists().values().toArray();
var numElements = c.length;
for( var i = 0; i < numElements; ++i){
gs.print(i+": "+c[i]);
}
var now_GR = new GlideRecord('incident');
var c = now_GR.getRelatedTables().values().toArray();
var numElements = c.length;
for( var i = 0; i < numElements; ++i){
gs.print(i+": "+c[i]);
}
var numberOfIncidents = new GlideRecord('incident');
numberOfIncidents.query();
gs.info("Records in incident table: " + numberOfIncidents.getRowCount());
gs.log('Table: ' + current.getTableName());
var now_GR = new GlideRecord('kb_knowledge');
now_GR.query();
now_GR.next();
var uniqueid = now_GR.getUniqueValue();
gs.info(uniqueid);
var now_GR = new GlideRecord('to_do');
now_GR.initialize();
now_GR.name = 'first to do item';
now_GR.description = 'learn about GlideRecord';
now_GR.insert();
var now_GR = new GlideRecord("sys_user");
now_GR.newRecord();
now_GR.setValue("user_name", "John Smith");
gs.print("Is this a new record: " + now_GR.isNewRecord());
var inc = new GlideRecord('incident');
inc.initialize();
inc.short_description = 'New incident 1';
inc.caller_id.first_name = 'John';
inc.caller_id.last_name = 'Doe';
inc.insertWithReferences();
var inc = new GlideRecord('incident');
inc.initialize();
inc.short_description = 'New incident 1';
inc.caller_id.setDisplayValue('David Loo');
inc.caller_id.first_name = 'John';
inc.caller_id.last_name = 'Doe';
inc.insertWithReferences();
var now_GR = new GlideRecord("sys_user");
now_GR.newRecord();
now_GR.setValue("user_name", "John Smith");
gs.print("Is this a new record: " + now_GR.isNewRecord());
var now_GR2 = new GlideRecord("sys_user");
now_GR2.addQuery("user_name", "Abel Tutor");
now_GR2.query();
now_GR2.next();
gs.print("Is this a new record: " + now_GR2.isNewRecord());
var testTable = new GlideRecord('incident');
gs.print(testTable.isValid());
si.isValidField('sys_class_name')
if(myObj.next()) construct only processes the first record returned.var rec = new GlideRecord('incident');
rec.query();
while (rec.next()) {
gs.print(rec.number + ' exists');
}
This method fails if there is a field in the table called “next”. If that is the case, use the method _next().
var rec = new GlideRecord('sys_template');
rec.query();
while (rec._next()) {
gs.print(rec.number + ' exists');
}
var count = 0;
var child = new GlideRecord('pm_project_task');
child.addQuery('parent', project.sys_id);
child.orderBy('order');
child.orderBy('number');
child.query();
var len = child.getRowCount().toString().length;
var seq = 0;
while (child.next()) {
count += UpdateProjectTaskWBS(child, 1, ++seq, len, '');
}
gs.addInfoMessage(count + ' Project Tasks updated');
current.setAbortAction(true);
var now_GR = new GlideRecord('incident');
now_GR.orderByDesc('sys_created_on');
now_GR.setLimit(10);
now_GR.query();
var task = new GlideRecord ('task');
var tsk_id = task.setNewGuid();
task.description = "Request: " + current.request.number;
task.description = task.description + "\n" + "Requested by: " + current.request.u_requested_by.name;
task.description = task.description + "\n" + "Requested for: " + current.request.u_requested_for.name;
task.description = task.description + "\n" + "Item: " + current.cat_item.name;
var now_GR = new GlideRecord ('task_rel_task');
//link the incident to the request
now_GR.parent = current.request;
now_GR.child = tsk_id;
now_GR.insert();
ci.setNewGuidValue(sys_id);
var now_GR = new GlideRecord("oauth_credential");
var oauthClient = now_GR.addJoinQuery("oauth_entity", "peer", "sys_id");
now_GR.addQuery("type", "access_token");
now_GR.addQuery("expires", ">", nowDateTime());
now_GR.addNullQuery("oauth_requestor_profile");
oauthClient.addCondition("active", "true");
oauthClient.addCondition("type", "client");
now_GR.setUseEngines(false);
now_GR.setWorkflow(false);
now_GR.query();
return now_GR.hasNext();
Sets the specified field, or an attribute in a dynamic attribute store, to a specified value.
When setting a value, ensure that the data type of the field matches the data type of the value you enter.
If the value parameter is null, the record isn’t updated, and an error isn’t thrown.
var now_GR = new GlideRecord('incident');
now_GR.addQuery('active', true);
now_GR.setValue('state', 4);
now_GR.updateMultiple();
If processing an incident where the Caller ID is set to reference sys_user record ‘John Doe,’ then the following code would update John Doe’s user record. If processing an incident where there is no Caller ID specified, then the following code would create a new sys_user record with the provided information (first_name, last_name) and set the Caller ID value to the newly created sys_user record.
var inc = new GlideRecord('incident');
inc.get(inc_sys_id); // Looking up an existing incident record where 'inc_sys_id' represents the sys_id of a incident record
inc.caller_id.first_name = 'John';
inc.caller_id.last_name = 'Doe';
inc.updateWithReferences();
}
var now_GR = new GlideRecord("incident");
now_GR.addQuery("sys_id", "<sys_id_value>");
now_GR.query();
if(now_GR.next()){
now_GR.work_notes.setJournalEntry("Content of the journal entry.", "abel.tuter");
now_GR.update();
}
var notes = current.work_notes.getJournalEntry(-1);