Create composite primary key

eashwar
Tera Contributor

Hello Team,

Can we have composite primary key created for a table ?

Table : sys_group_has_role

Composite Primary Key : Group, Role

Reason why we are adding it to avoid duplicate group role entry for same group.

Thank you,

Eashwar

2 REPLIES 2

Madhu80
ServiceNow Employee
ServiceNow Employee

Eashwar, if you are using Fuji or a later release you may refer to Unique Index and Adding a Database Index


Steven24
Kilo Contributor

Here is an example of a buisness rule with a table called KeyValueStore that has the columns of entitytype and entityreference that if both columns have values that exist in a record then the update or insert aborts:

  1. Create a business rule in Studio.  Give it a Name and for Table select the table to apply the business rule to.  Check Advanced.
  2. On the When to run tab select 'before' for when and check Insert and Update.
  3. On the Actions tab check Add message and in Message enter a message.  In my example I entered "Entity Reference and Entity Value already exist in table."
  4. On Advanced in Script I created the following script: 

 

(function executeRule(current, previous /*null when async*/ ) {
var gr = new GlideRecord('x_kmhus_snxt_toolk_keyvaluestore');
gr.addQuery('entitytype', current.entitytype);
gr.addQuery('entityreference', current.entityreference);
gr.query();
while (gr.next()) {
if(gr.sys_id != current.sys_id){
current.setAbortAction(true);
}
}
})(current, previous);

Hope this example helps anyone trying to create a composite key on a SN table.