I need to set an unique number with rang from 1-99 for each transaction, says,
- Transaction 1: seq_num = 1;
- Transaction 2: seq_num = 2;
- …
- Transaction 99: seq_num = 99;
- Transaction 100: seq_num = 1; (rollover)
I am thinking to create a MySQL table named SEQ_NUM, with only field named ‘id’, so every time, I can run the following sql,
Update SEQ_NUM set id = id + 1;
to get an seq_num, if seq_num = 100, then I will set seq_num =1 and run another sql to reset id as,
Update SEQ_NUM set id = 1;
But I am not sure it is guarantee working, because there could be more than one transaction running at the same time, and before I run
Update SEQ_NUM set id = 1;
There could be another transaction asking for a sequence number, and the 101 will be returned.
Any idea?
Thanks!
I think the modulus operator is of use here. Perhaps the basic idea you have will work, but allow that SEQ_NUM to grow unbounded, and when you select it for your sequence number, wrap it in MOD().
But in reality, I would wonder if you already had a unique & auto-incrementing ID column which could be used this way (i.e.
SELECT MOD(id, 99) as trans_seq)…