简体   繁体   中英

what is a good way to provide a range of unique numbers (C# vs Sql)?

i have to provide a unique number to clients of my app. It's an invoice number, so it has to be unique, and thread safe off course.

In the past i created a singleton and used a lock statement: during the lock i would go to the database and get a new number and then release the lock.

Something is telling me that this could also be done in SqlServer, but in SqlServer i assume i also have to create some kind of lock because the sql code (stored procedure) can be executed in parallel also i guess.

So when i have to provide a lock anyway, does it make a difference wether i do it in c# or in Sql?

Use an identity column in SQL Server:

-- Set up
create table UniqueNumberGenerator (UN int identity primary key)

-- Generate value
insert into UniqueNumberGenerator default values
select scope_identity()

This is faster and more lightweight than acquiring a lock on a table. See here for the dirty details.

If you are concerned about the table filling up with thousands of rows, worry not, you can periodically delete all rows from the table, and SQL Server will still remember the next value to be generated. You can reset the generated value with dbcc checkident if you need to.

The only solution I know of that can reliably produce unique numbers in isolation is the GUID data type. Trouble is, that's too long to be used easily as an order number.

Using the database to get the next number from an identity field means you do not have to manage the locks, simply perform an insert and the DB will provide the next number.

Of course, if the invoice is not then saved the number has been used and is now "lost". If that does not bother you then I would use that method. Doing it in code is a pain, plus what happens when more than on instance of your application is running? You could get the same number generated.

If you can deal with its awful look, the database's timestamp is thread safe : SELECT @@dbts

(You can trim the leading zeros to have it look more like an acceptable invoice id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM