Tuesday, 24 March 2015

Generate random password alphanumeric with special char in sql server

CREATE VIEW dbo.vw_Randomizer
AS
SELECT RAND() as RandNumber
GO

DECLARE @template VARCHAR(30),
@result NVARCHAR(4000)

SELECT  @template = 'cAd0Pf6g',
@result = ''

DECLARE
@i INT,
@c CHAR(1),
@password VARCHAR(30),
@special VARCHAR(50)


SELECT @i = 0,
@password = '',
@special = '_'

SET @i = 1

WHILE @i <= LEN(@template)
BEGIN

SET @c =
CASE
--upper alpha [A-Z]
WHEN ASCII(SUBSTRING(@template, @i, 1)) BETWEEN 65 AND 90
THEN CHAR(65 + CONVERT(INT,FLOOR((SELECT RandNumber FROM dbo.vw_randomizer)*26)))

--lower alpha [a-z]
WHEN ASCII(SUBSTRING(@template, @i, 1)) BETWEEN 97 AND 122
then CHAR(97 + CONVERT(INT,FLOOR((SELECT RandNumber FROM dbo.vw_randomizer)*26)))
--number [0-9]
WHEN ASCII(SUBSTRING(@template, @i, 1)) BETWEEN 48 AND 57
THEN CONVERT(char(1), CONVERT(INT,FLOOR((SELECT RandNumber FROM dbo.vw_randomizer) * 10)))
--special (printable) character
ELSE
SUBSTRING(@special, CONVERT(INT,FLOOR(((SELECT RandNumber FROM dbo.vw_randomizer)*LEN(@special))+1)), 1)
END

SELECT @i = @i + 1,
@password = @password + @c
END

SELECT @result = @password

RETURN @result

------
DECLARE @template VARCHAR(30)

SELECT  @template = 'cAd0P*f6g'

DECLARE
@i INT,
@c CHAR(1),
@password VARCHAR(30),
@special VARCHAR(50)


SELECT @i = 0,
@password = '',
@special = '~!@#%&_<>'

SET @i = 1

WHILE @i <= LEN(@template)
BEGIN

SET @c =
CASE
--upper alpha [A-Z]
WHEN ASCII(SUBSTRING(@template, @i, 1)) BETWEEN 65 AND 90
THEN CHAR(65 + CONVERT(INT,FLOOR((SELECT MyRAND FROM Get_RAND)*26)))

--lower alpha [a-z]
WHEN ASCII(SUBSTRING(@template, @i, 1)) BETWEEN 97 AND 122
then CHAR(97 + CONVERT(INT,FLOOR((SELECT MyRAND FROM Get_RAND)*26)))
--number [0-9]
WHEN ASCII(SUBSTRING(@template, @i, 1)) BETWEEN 48 AND 57
THEN CONVERT(char(1), CONVERT(INT,FLOOR((SELECT MyRAND FROM Get_RAND) * 10)))
--special (printable) character
ELSE
SUBSTRING(@special, CONVERT(INT,FLOOR(((SELECT MyRAND FROM Get_RAND)*LEN(@special))+1)), 1)
END

SELECT @i = @i + 1,
@password = @password + @c
END

SELECT @password

No comments:

Post a Comment

Get all non-clustered indexes

DECLARE cIX CURSOR FOR     SELECT OBJECT_NAME(SI.Object_ID), SI.Object_ID, SI.Name, SI.Index_ID         FROM Sys.Indexes SI             ...