How to make the Auto Increment correctly

ursnani
Giga Guru

Hi All,

I have a field on my Table which is  a integer field and is at the backend only.

now My Req is I have to auto increment the number from 1 when a record is inserted and i was able to do that by usinf Before Insert BR.

Now my challenge is I have to handle the deleted Number and it should not effect the Increment of my Number.

Example:

I have inserted 3 records and my field has been auto populated as follows

Record 1: field value =1

Record 2: field value =2

Record 3: field value =3

now If i delete the Record  2 The field Count value 2 will be delete.

Now I have created a new record and the field value should be 4 but not 3.

below is the BR i have written.

var gr = new GlideRecord('u_table');
gr.orderByDesc('u_field_count');
gr.query();

if(gr.getRowCount()>=0){

current.u_field_count= gr.getRowCount()+1;
}

 

any suggestion on this

 

Thanks

3 REPLIES 3

Ct111
Giga Sage

Hi ,

 

I would insist you on using  setLimit(1) in your query after orderByDesc('u_field_count')

 

as a result you will get the expected result.

 

If you face any issue in query refer the below link for example

 

https://community.servicenow.com/community?id=community_question&sys_id=d7574769db1cdbc01dcaf3231f961952

 

Mark my ANSWER as CORRECT and HELPFUL if it helped

if i use that then the count is always 2 regardless of how many records i am inserting.

var gr = new GlideRecord('u_table');
gr.orderByDesc('u_field_count');

gr.setLimit(1);

gr.query();

if(gr.u_field_count> 0){

current.u_field_count= gr.u_field_count+1;
}

 

Try the below code and let me know if it works

 

Mark my ANSWER as CORRECT and HELPFUL if it helps