Question

I need to generate a 9 digit order id without any leading zeroes. What is the best way to do this ?

What I think of is: Create a Table with a unique ID Column and then generate a random number between 100000000 and 999999999 in C# Code and try to insert it into the table until I am successful. What are the chances of getting Unique Constraint Exception in this and re-generating the number ?

If I am thinking in the right direction, is there any way to do this in the sql server itself rather than handling exception in the C# code and then re-generating ?

Or is there any other best method to do this ?

Thanks

Was it helpful?

Solution

generate ... until I am successful.

Well. It would probably even work if number of your transactions would remain relatively low compared to all the possibilities, but that seems really wrong. Catching exceptions and retrying?

Do you have any reasons not to use autoincrement key, starting with 100000000 and counting?

OTHER TIPS

You can use identity seed feature in SQL Server and define the starting value http://msdn.microsoft.com/en-us/library/aa933196(v=sql.80).aspx

If your goal is to generate a seemingly random, unique transaction ID, I suggest using parts from the transaction owner (userid) and parts from the transaction itself and combine those to generate your unique transactionid. If that's not possible, then I suggest converting a GUID to a decimal. Here's how to do it: Converting System.Decimal to System.Guid

If you have a compelling reason for wanting the IDs to be in random order, maybe you could write a one-time utility program in C# to generate the random list of numbers and insert them into a SQL table. Then, when your program needs an ID, it can select the next available one from that table. Of course, you'd need a bit field or something to mark which IDs have been used. You might want to put the select and mark operations into a stored procedure and have the procedure lock the table while it's working so simultaneous processes don't get the same ID before they've had a chance to mark it as used.

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