Technical Article

Generate Random Alphanumeric String

,

Here's a short script to generate a random alphanumeric string based on newid(). The procedure takes in length (@len) which determines the key length. Length must be between 8 and 32. Result is returned in an output parameter. A test script is supplied.

ALTER PROC GenRandomKey (@len TINYINT = 8, @ret VARCHAR(32) OUT)
AS
SET NOCOUNT ON
IF @len <8 or @len > 32 
RAISERROR('Key length must be between 8 and 32',16,1)
ELSE
SET @ret = left(replace(newid(),'-',''),@len)

go


declare @ret varchar(32)
exec GenRandomKey 32, @ret out
print @ret

Rate

3.67 (3)

You rated this post out of 5. Change rating

Share

Share

Rate

3.67 (3)

You rated this post out of 5. Change rating