T-SQL: Most easy way to create random passwords!
A common asked question is, how random passwords can be generated with a simple T-SQL statement. Many blogs cover this topic, but it's hard to get an easy answer. I think the following script is the most simple approach. If you have a simpler way, please comment!
DECLARE @chars nvarchar(MAX) = ''
DECLARE @random int = 0
WHILE LEN(@chars) < 20
BEGIN
-- generate a random character, exclude characters : ; < = > ? [ \ ] `
GENERATE: SET @random=ROUND(RAND()*74,0)+48
IF @random in (58,59,60,61,62,91,92,93,96) GOTO GENERATE;
SET @chars = CONCAT(@chars, char(@random))
END
SELECT @chars
You can include/exclude additional characters by including or removing the ascii values from the IF statement.
How the script works:
``GENERATE: ``SET
@random=ROUND(RAND()*74,0)+48
Set a random value from 48 (0*74 + 48) to 122 (1*74 + 48). GENERATE: is a label which will be used in the next line to jump back, if the random value is within the unwanted list of character values:
``IF @random ``in
(58,59,60,61,62,91,92,93,96) ``GOTO
GENERATE;
The GOTO statement sets the interpreter to jump back to the GENERATE: label and to choose a different value.
Now, we just have to add the new random character to our @chars variable:
``SET
@chars = CONCAT(@chars, ``char``(@random)
I think the rest of this really small script is self-explaining.