I have a requirement to generate a semi-random code in C#/ASP.NET that has to be unique in the SQL Server database.
These codes need to be generated in batches of up to 100 codes per run.
Given the requirements, I'm not sure how I can do this without generating a code and then checking the database to see if it exists, which seems like a horrible way of doing it.
Here are the requirements:
- Maximum 10 characters long (alpha-numeric only)
- Must not be case sensitive
- User can specify an optional 3 character prefix for the code
- Must not violate 2 column unique constraint in the database, i.e. must be a unique "code text" within the "category" (
CONSTRAINT ucCodes UNIQUE (ColumnCodeText, ColumnCategoryId)
)
So, given the 10 character limit, GUIDs are not an option. Given the case insensitivity requirement, the mathematical probability for database collisions are fairly high, I think.
At the same time, there are enough possible combinations that a straight look-up table in the DB would be prohibitive, I believe.
Is there a reasonably performant way of generating codes with these requirements that doesn't involve saving them to the DB one code at a time and waiting for a unique key violation to see if it goes through?