I want to generate a unique 8 character random alphanumeric string in TSQL, for a mail confirm link. We are currently using a GUID but it is not very user friendly.
It only really has to obey a few rules:
- be 8 Characters long
- be unique
- be generated efficiently
Here are 2 ways of solving it
Method 1: This will generate 8 random characters and store them in varchar @r, in order to prevent all the individual characters from being identical, I added a seed to RAND().
Method 2: This method is using a tally table, each character will never occur more than once. The rows used to generate these characters are randomized by ordering on newid()
In order to ensure uniqueness for each varchar(8) you can store the results in a table and compare with result in that table. You can also make the varchar longer and just hope for the best