How to place a unique index on two fields in a table.

anjiadmin
Tera Expert

I have two   the fields   field 1,field 2 in a table.

I want to keep unique index on those two fields..

How can we achieve this?  

9 REPLIES 9

I suppose, there is no provision to change the message. However, we can detect that situation early and show a message. Create a client script for that table, use onSubmit event, make a call to server-side by passing 2 column values and record id. server side script include function checks and returns whether exists already or not. accordingly you will stop submit and show message as duplicate.



Client script:



function onSubmit() {


    //Type appropriate comment here, and begin script below


  var Col1 = g_form.getValue('u_col1');


  var Col2 = g_form.getValue('u_col2');


  var ga = new GlideAjax('Test');


  ga.addParam('sysparm_name','getReferenceTableRecs');


  ga.addParam('sysparm_col1',Col1);


  ga.addParam('sysparm_col2',Col2);


  ga.addParam('sysparm_id',g_form.getUniqueValue());


  ga.getXMLWait();


  var answer = ga.getAnswer();


  alert(answer);


  if(answer == "false")


  {


  alert("Duplicates exists")


  return false;


  }


  return true;


}



At server-side, create a script include like below.



var Test = Class.create();


Test.prototype = Object.extendsObject(AbstractAjaxProcessor, {


  getReferenceTableRecs: function()


  {


  var Col1 = this.getParameter('sysparm_col1');


  var Col2 = this.getParameter('sysparm_col2');


  var id = this.getParameter('sysparm_id');


  var gr = new GlideRecord('u_referencetable');


  gr.addEncodedQuery('u_col1=' + Col1 + '^u_col2=' + Col2);


      gr.query();


  while(gr.next())


  {


  gs.addInfoMessage(gr.sys_id);


  gs.addInfoMessage(id);


  if(gr.sys_id.toString() != id.toString())


  {


  return false;


  }


  }


  return true;


  },


      type: 'Test'


});


The best way is to create a before save BR and abort the operation if the data already exists in the database.

pawanbhatt
Tera Contributor

Hello All,

 

I am facing the same problem and both (BR and Data Policy) is of no use now. As both the hits are coming in at the same time from a Fault Management System. And they both are getting inserted into the system.

 

According to me, Composite Unique key is the only option. If that is not possible, is there any other way by which we can control this at System level.

You can add a composite unique index by editing the Table record and clicking on the "New" button in the "Database Indexes" Related List:

find_real_file.png 

 

You get a popup window where you define the fields you want to be part of the index:

find_real_file.png

 

Move the fields from the "Available" list over to the "Selected" list and make sure you select the "Unique Index" checkbox.

Hi Jim,

I tried this, but it doesn't seem to work for composite key.

The combination of the columns uniqueness are not taken into account.

Regards,

Swarnadeep Nandy