Certainly! Writing a background script in ServiceNow to cancel tasks across related tables involves identifying the parent-child relationships and ensuring that each related task is handled accordingly.
In your scenario:
- The parent table is ARR.
- HARL table has one child record related to the parent.
- HART table contains more related tasks.
Here's a general approach to accomplish this in a background script:
- Query the ARR table for the tasks you want to cancel.
- Cancel the tasks in ARR.
- Find the related HARL record and cancel it.
- Find and cancel related HART records based on the HARL record.
Sample Background Script
// Ensure glideRecord and gs are available
(function() {
// Define the cancellation function
function cancelRecord(gr) {
if (gr) {
gr.setValue('state', 'canceled'); // Assuming 'state' and 'canceled' are appropriate field and value
gr.update();
}
}
// Get the tasks from the ARR table that need to be canceled
var arr = new GlideRecord('u_arr'); // Replace 'u_arr' with the actual ARR table name
arr.addQuery('state', 'active'); // Assuming you want to filter active tasks
arr.query();
while (arr.next()) {
gs.info('Cancelling ARR Task: ' + arr.sys_id);
cancelRecord(arr);
// Get the related HARL record
var harl = new GlideRecord('u_harl'); // Replace 'u_harl' with the actual HARL table name
harl.addQuery('u_arr', arr.sys_id);
harl.query();
if (harl.next()) {
gs.info('Cancelling HARL Task: ' + harl.sys_id);
cancelRecord(harl);
// Get related HART records
var hart = new GlideRecord('u_hart'); // Replace 'u_hart' with the actual HART table name
hart.addQuery('u_harl', harl.sys_id);
hart.query();
while (hart.next()) {
gs.info('Cancelling HART Task: ' + hart.sys_id);
cancelRecord(hart);
}
}
}
})();
gs.info('Background script completed successfully.');
Points to Consider
- Table Names: Replace
'u_arr', 'u_harl', and 'u_hart' with the actual table names. Prefixes like u_ might or might not be necessary depending on your instance.
- Fields: Adjust the fields such as
state and the state value 'canceled' to match your actual table structure and business logic.
- Query Filters: Modify the query filters (
'state', 'active', etc.) based on the criteria that match your use case.
- Error Handling: This script doesn't include detailed error handling. Consider enhancing it to handle edge cases.
- Performance: For a large number of records, ensure that this script doesn't breach transaction quotas or performance limits.
Always test such scripts in a development or test instance before running them in a production environment to avoid any unintended consequences.