How to run business rules?

zsquared
Tera Contributor

Hello,

I am trying to run the following business rule to update or insert a record into my table: u_lol_databases

I placed the following script in the u_lol_databases business rules.   I also used the condition onDisplay.. assuming the table will update the correct count if I view the u_lol_databases table.

//count the number of different sys_class_names in the cmdb_ci_db_ora_instance table

var agg = new GlideAggregate('cmdb_ci_db_ora_instance');

agg.addAggregate('COUNT', 'sys_class_name');

agg.groupBy('sys_class_name');

agg.query();

while (agg.next()) {

  var databaseType = agg.sys_class_name.getDisplayValue();

  var hierarchy = new GlideRecord('u_lol_databases');

  hierarchy.addQuery('u_database_type',databaseType);

  hierarchy.query();

  var getCount = agg.getAggregate('COUNT', 'sys_class_name');

  if (hierarchy.next()) {

  hierarchy.u_count = getCount;

  hierarchy.update();

  } else {

  hierarchy.u_database_type = databaseType;

  hierarchy.u_count = getCount;

  hierarchy.insert();

  }

}

I'm not really sure where my logic is wrong.   I am fairly new to ServiceNow.   Capture.PNGAny advice?

1 ACCEPTED SOLUTION

Chuck Tomasi
Tera Patron

Hi Zhen,



Business rules are triggered from database operations (insert, update, delete, query). They can happen at various stages when a record is displayed or updated.



A Display business rule is probably not the right place to run an insert/update as it runs every time a form is loaded. When you see the record, the business rule runs. You likely want an after BR used to affect other records after you update the current record. See the video in the second line of when to run business rules and I think you'll get the idea.



Reference:


Business Rules - ServiceNow Wiki


Business Rules Best Practices - ServiceNow Wiki  


View solution in original post

6 REPLIES 6

You are very welcome. I'm glad you got it resolved.


If I have answered your question, please mark my response as correct so that others with the same question in the future can find it quickly and that it gets removed from the Unanswered list.



If you are viewing this from the community inbox you will not see the correct answer button.   If so, please review How to Mark Answers Correct From Inbox View.



Thank you


SaschaWildgrube
ServiceNow Employee
ServiceNow Employee

To identify the business rules and flows that run on a record when inserting, updating, deleting, displaying or querying the record the DevTools' WhatRuns button comes in handy.

As the name suggests it shows you what runs on a record (including business rules on parent tables).

DevTools contains a truckload of re-usable functions and features for developers.

Fork at will:

https://github.com/saschawildgrube/servicenow-devtools