uniqueness of name using business rule

RudhraKAM
Tera Guru

I have a requirement to create before insert  business rule  to Enforce Uniqueness of Name on Server Class Table and Child Server Class Tables .which will produce an error on insert or update after checking for a duplicate name. The code should check all server class CIs (and child server class CIs) , and ensure that there are no other servers with the same name. It must check the name value in a case insensitive test. If a duplicate is found, an error should pop up and indicate 'Another server CI already has that name' and prevent submission of the record.

 

Can some one help me with this , thanks in advance.

1 ACCEPTED SOLUTION

Shishir Srivast
Mega Sage

You can have before update/insert BR on cmdb_ci_server table with below script:

(function executeRule(current, previous /*null when async*/) {
	var uniqueNameGR = new GlideRecord('cmdb_ci_server');
	uniqueNameGR.addQuery('name', current.name);
	uniqueNameGR.addQuery('sys_id', '!=', current.getUniqueValue());
	uniqueNameGR.query();
	if (uniqueNameGR.getRowCount() > 0) {
		gs.addErrorMessage(gs.getMessage("Server with name '{0}' already exists.", current.name));
		current.setAbortAction(true);
	}
})(current, previous);

View solution in original post

3 REPLIES 3

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Kam,

Why not mark that field as unique at table level and it should take care. But there you cannot give custom message.

if custom message is required then have before insert/update business rule query the table and if name already found use 

current.setAbortAction(true);

gs.addInfoMessage("Another server CI already has that name");

Mark Correct if this solves your issue and also mark Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

when i try to add the unique and check and save its showing an error stating that there are already duplicates delete them and try again ,, how to check which one is the duplicate there are more than 20 k records and i grouped by name , which is giving me only 3 difference (meaning there are only 3 duplicates ) , do you know the simple way to find them ?

Shishir Srivast
Mega Sage

You can have before update/insert BR on cmdb_ci_server table with below script:

(function executeRule(current, previous /*null when async*/) {
	var uniqueNameGR = new GlideRecord('cmdb_ci_server');
	uniqueNameGR.addQuery('name', current.name);
	uniqueNameGR.addQuery('sys_id', '!=', current.getUniqueValue());
	uniqueNameGR.query();
	if (uniqueNameGR.getRowCount() > 0) {
		gs.addErrorMessage(gs.getMessage("Server with name '{0}' already exists.", current.name));
		current.setAbortAction(true);
	}
})(current, previous);