avoid duplicate entry in a table by business rule

Raju Singh1
Tera Expert

I am trying to avoid a duplicate entry in a table using a business rule but it is not working.

Instead of firing for duplicate entires.. Its fires for everything. even not allowing me to add the fresh entry itself.

I am trying to eliminate a duplicate entry for a serial no. in a computer table.

Here is my code:

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

// Add your code here

var gr = new GlideRecord('cmdb_ci_computer');

gr.addQuery('serial_number', current.serial_number);

gr.query();

if(gr.next()){

gs.addInfoMessage('There is duplicate value for this serial number in the table');

current.setAbortAction(true);

}

})(current, previous);

1 ACCEPTED SOLUTION

snehabinani26
Tera Guru

Hi Raju,



You can have a before BR with the below script.



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


  var grAst = new GlideRecord('cmdb_ci_computer');


  grAst.addQuery('serial_number', current.serial_number);


  grAst.query();


  if (grAst.next() && grAst.sys_id != current.sys_id) {


      gs.addErrorMessage("Serial number already exists");


      current.setAbortAction(true);


  }


})(current, previous);



Hope this helps you.


View solution in original post

24 REPLIES 24

Its working for me. Check if you selected When = Before and Insert and Update are selected.


Still it just checks for the serial no. and does a correct check but it doesnt allow me to enter the value of other fields in the first attempt. Please see my screenshots


marcguy
ServiceNow Employee
ServiceNow Employee

I would suggest adding another message to see if it is finding a particular record i.e.



gs.addErrorMessage('I found this computer: ' + gr.name + ' - ' + gr.sys_id);



just to see what it is finding as a duplicate


Dave Smith1
ServiceNow Employee
ServiceNow Employee

Raju Sardar wrote:



I am trying to avoid a duplicate entry in a table using a business rule


Does it need to be a business rule?



Making a field (or combination of fields) unique should prevent duplicates.


Yes you are right Dave, but as there are already duplicate entries.. I was just afraid that I may loose some data if I make it unique value now. What's the best practice?