Monday, October 22, 2012

Generate Random value

Wonder how random confirmation numbers are generated? Here is one way to generate. This code will exclude all the special characters and consider values from 0-9 and [a-z]/[A-Z]. But the final result will be all UPPER case characters.


 DECLARE @Lenght INT = 6
 DECLARE @OutPut VARCHAR(10) = ''
 DECLARE @ExcludeList VARCHAR(100) = '~`!@#$%^&*()_-+={[}]|\:;"''?/>.<,'
 DECLARE @CharList CHAR

 WHILE (@Lenght >0)
 BEGIN
        SET @CharList = CHAR(RAND() * 72 + 48)
        IF CHARINDEX(@CharList,@ExcludeList) = 0
        BEGIN
               SELECT @OutPut = @OutPut + @CharList
               SET @Lenght = @Lenght - 1
        END
 END

 SELECT UPPER(@OutPut)