Question

I need to assign a number to a document - an RFQ, quote, order, job, etc. The table that will hold this number has a primary key field of type integer, flagged as identity so it will increment automatically. Should I use the value of this field as my serial number, or is it better to have a different field SN of type integer and assign a new record the value max(SN) + 1? Or is there a better way than either of these?

Was it helpful?

Solution

I have often used something like this. Assume that the MyIDValues table has only one row, so IDColumn always holds the most-recently-assigned ID value:

DECLARE @NewID Int
UPDATE MyDB.dbo.MyIDValues SET @NewID = IDColumn = IDColumn + 1
SELECT @NewID

It simultaneously (i.e. as an atomic statement) updates the table to set the incremented value and returns that value.

In my opinion, this is better than taking the current top value because it always avoids collisions (i.e. if you have software that incorrectly does take the top value) by incrementing first and then returning that incremented value.

OTHER TIPS

Use a hash (ie. md5, most languages support this natively) of some idiosyncratic property of the item.

For example, if you have a table of items in a MySQL database, each one probably has an id number that's unique but of no use as a serial number. But a hash will always give you a string of a set length that is also unique, so in php, for example, $code = md5($id); (e-mail addresses also work, but you should salt anything remotely personal).

The other trick is to carry meaningful data inside a code by stringing together non-sensitive data, like data, time, product item into "20140101183263-006".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top