Tuesday, June 28, 2011

How to generate an AutoAlphaNumeric Code in SQL

-- To know @ just copy & paste

declare
@sLength tinyint,
@AutoCode varchar(50)

set @sLength = 8 -- Can be changed

DECLARE @counter tinyint
DECLARE @nextChar char(1)

set @AutoCode = ''

SET @counter = 1

WHILE @counter <= @sLength
BEGIN
SELECT @nextChar = CHAR(48 + CONVERT(INT, (122-48+1)*RAND()))

IF ASCII(@nextChar) not in (58,59,60,61,62,63,64,91,92,93,94,95,96)
BEGIN

SELECT @AutoCode = @AutoCode + @nextChar
SET @counter = @counter + 1

END
END

select @AutoCode AutoCode,UPPER(@AutoCode) 'AutoCode(Upper)',LOWER(@AutoCode) 'AutoCode(Lower)'

No comments:

Post a Comment