Update multiple records in incident table using business rules

Sridhar32
Tera Contributor

In the incident table I want to update 'state' to closed from new using business rules.

(function executeRule(current, previous /*null when async*/ ) {

    var inc = new GlideRecord('incident');
    inc.addQuery('state=1');

    inc.query();

    while (inc.next()) {

        inc.setValue('state',7);

        inc.setValue('close_code','User error');

        inc.setValue('close_notes','test');


        inc.setWorkflow(false);


        inc.autoSysFields(false);


        inc.update();
    }

})(current, previous);
 
This is the query i have used but it did not updated state to closed when i save this query, can any one please help.
2 REPLIES 2

Deepak Shaerma
Kilo Sage

Hi @Sridhar32 

The code snippet you’ve provided is meant to be part of a Business Rule but contains a significant logical flaw when it comes to updating records in ServiceNow.

Here’s how you could structure the Business Rule to close an incident:

1. Go to System Definition > Business Rules.
2. Create New Business Rule with the following suggested settings (you may adjust based on your requirement):
Name: Auto Close New Incidents
Table: Incident [incident]
When to run the rule: Decide when the rule should run. For an auto-close functionality, you might want to set it before Update or before insert based on your use case. You might also want to add a condition that checks if the incident is in the ‘New’ state.
Filter Conditions: State is New

(function executeRule(current, previous) {
    // Check if the incident is in the New state (state=1)
    // Note: Ensure this matches your instance’s value for the ‘New’ state if customized
    if (current.state == '1') {
        current.state = '7'; // Update state to Closed
        current.close_code = 'User error'; // Set the close code
        current.close_notes = 'Automatically closed by system due to user error.'; // Set close notes
    }
})(current, previous);


Workflow and System Fields: The script uses direct updates without disabling workflow (setWorkflow(false)) or system fields auto-population (autoSysFields(false)), as typically these are desired to keep historical tracking accurate. Adjust accordingly if you have specific needs, but be cautious about bypassing these mechanisms.

Note: Please Mark this Helpful and Accepted Solution. If this Helps you to understand. This will help us a lot.
Thanks & Regards 
Deepak Sharma


shikhatyagi
Kilo Sage

Hi @Sridhar32 

 

Your script is correct but you have written it in Business Rule. Business rule will execute only if there is any update on the incident.

So, write the same code in the scheduled job and run it on daily basis. 

 

Please Mark this Helpful and Accepted Solution if it solves your issue.

 

Thanks & Regards,

Shikha Tyagi