posted 5/16/2010 by Raghav Khunger
Today I was in a need to make a function which can generate random n digit alphanumeric string of desired length in SQL. I am writing this blog to show what I did to accomplish the same. The function accepts one parameter of integer type and will return the desired length alphanumeric output. The input parameter represents the length of the alphanumeric string which is desired .
Below is the script for the FUNCTION:
CREATE FUNCTION [GenerateRandomNumber] ( @LENGTH INT ) RETURNS NVARCHAR(255) AS BEGIN --DECLARE VARIABLES DECLARE @RandomNumber NVARCHAR(255) DECLARE @I SMALLINT DECLARE @RandNumber FLOAT DECLARE @Position TINYINT DECLARE @ExtractedCharacter VARCHAR(1) DECLARE @ValidCharacters VARCHAR(255) DECLARE @VCLength INT --SET VARIABLES VALUE SET @ValidCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' SET @VCLength = LEN(@ValidCharacters) SET @ExtractedCharacter = '' SET @RandNumber = 0 SET @Position = 0 SET @RandomNumber = '' SET @I = 1 WHILE @I < ( @Length + 1 ) BEGIN SET @RandNumber = ( SELECT RandNumber FROM [RandNumberView] ) SET @Position = CONVERT(TINYINT, ( ( @VCLength - 1 ) * @RandNumber + 1 )) SELECT @ExtractedCharacter = SUBSTRING(@ValidCharacters, @Position, 1) SET @I = @I + 1 SET @RandomNumber = @RandomNumber + @ExtractedCharacter END RETURN @RandomNumber END
In the above function I have used a VIEW named RandNumberView. Script of RandNumberView
CREATE VIEW [RandNumberView] AS SELECT RAND() AS [RandNumber]
You may be thinking Why I have used it? , the answer is I need to use the random number if I had used rand() simply in the function I would have received this error "Invalid use of side-effecting or time-dependent operator in 'rand' within a function". Okay now lets test the function:
SELECT DBO.[GenerateRandomNumber](2) --OUTPUT ----------------------------------------- --gB SELECT DBO.[GenerateRandomNumber](5) --OUTPUT ----------------------------------------- --JfAql SELECT DBO.[GenerateRandomNumber](10) --OUTPUT ----------------------------------------- --QTFqjmivWW SELECT DBO.[GenerateRandomNumber](20) --OUTPUT ----------------------------------------- --iZQRCEfQuTeYHLnikbWl
Do let me know your feedback, comments.
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18