Generating unique random numbers in VB.NET

I have a table that gets a row populated to it with a piece of code..one of the fields in the table holds a 4 digit number that is generated with a random number function. What I was wondering was I want to generate a number that has not been used before?

I was thinking of creating a view of the numbers that are already used...compare that with the new number that is generated and see if it exists in the view ..if a good number ..continue on with the code ..if a bad number generate again and compare again..etc..

 Just wondering if this is the best approach...

Any help would be much appreciated..
nomar2Asked:
Who is Participating?
 
Jeff CertainCommented:
I think this is a weak approach. Part of the reason that I say this is that you're limited yourself to no more than 10K records, which seems like you're painting yourself into a corner.
In general, when guaranteed uniqueness is the requirement, a GUID is a quick and effective way to go.
Otherwise, is the table entirely in memory, or is it only complete at the database? How many concurrent users are you looking to support? If it's more than one, you'll have concurrency issues around the guaranteed uniqueness problem.
0
 
Paul_Harris_FusionCommented:
At initial reading, this does not seem like the best approach.  

Does the value need to be random?  Can you use autonumber fields or sequences at the table level?

if you need the id to be generated in memory,  can you use GUIDs instead of 4 digit integers?

My concern is that as the table fills up, you will have more and more failed attempts to find an unused number until when you have 9999 records, the table is effectively full and you will be unable to put any more in.

If you must do thi
0
 
nomar2Author Commented:
I will have to reevaluate this...never thought about the numerous failed attempts as the table fills up...

Maybe I will have to increase the range from 1000 to 99999..the 4 digit number is used as a login to a registration page on the web..they setup their own password..Maybe I will make them setup a unique username too on the web when they do their password..

Thanks for the input...
0
 
Jeff CertainCommented:
I would allow them to set their user name ... it makes it more likely that they'll remember it!
Plus, I believe there's an ASP.NET membership provider that handles much of that login/registration logic for you.
0
 
Jeff CertainCommented:
Here's an MSDN article about the membership provider I mentioned. It's a little dated, but should be essentially correct still.  http://msdn.microsoft.com/en-us/library/ms998347.aspx
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.