I'm trying to create a stored procedure to randomly generate two unique alphanumeric characters from the following character set on SQL Server 2016: ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789 (35-character set). The random values will then be stored on a custom column on the AspNetUsers table.
Currently, only 132 unique 2-character values are stored on the AspNetUsers table, while there can be a total of 1,225 permutations. This is based on the permutations formula: n! / (n - r)! or 35! / (35 - 2)! = 1225.
The following code, based on this example works sometimes, while other times, it becomes an infinite loop. The outer WHILE ensures the value is unique on the table where it will be stored.
DECLARE @length int, @charpool varchar(256), @poollength int,
@loopcount int, @randomstring varchar(100)
SET @Length = 2
-- define allowable character explicitly - easy to read this way an easy to
SET @CharPool = 'ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789'
SET @PoolLength = Len(@CharPool)
SET @LoopCount = 0
SET @RandomString = ''
WHILE (SELECT count(*) FROM AspNetUsers anu WHERE anu.CustomId = @randomstring) > 0 BEGIN
WHILE (@LoopCount < @Length) BEGIN
SELECT @RandomString = @RandomString +
SUBSTRING(@Charpool, CONVERT(int, RAND() * @PoolLength) + 1, 1)
SELECT @LoopCount = @LoopCount + 1
END
END
PRINT @randomstring
@randomstringand@loopcountafter the first while, so once you set a random value that exist, you continue to loop until forever. Btw you don't need to loop to make this work, unless you use it to keep the server room warm