How to Generate Random Password in SQL Server? – Interview Question of the Week #181

Question: How to Generate Random Password in SQL Server?

Answer: This is a fantastic question and here is the script to generate a random password in SQL Server

DECLARE @char CHAR = ''
DECLARE @charI INT = 0
DECLARE @password VARCHAR(100) = ''
DECLARE @len INT = 12 -- Length of Password
WHILE @len > 0
BEGIN
SET @charI = ROUND(RAND()*100,0)
SET @char = CHAR(@charI)

IF @charI > 48 AND @charI < 122
BEGIN
SET @password += @char
SET @len = @len - 1
END
END
SELECT @password [PassWord]

How to Generate Random Password in SQL Server? - Interview Question of the Week #181 randompassword-800x511

Well, that’s it. It will generate a password with alphabets, numerics, and special characters. If you want to change the length of the password, you can easily do so by changing the parameter @len. Please note that this function is based on the random function so you will probably never get the same password again in the near future. Here are the sample 10 passwords I generated from the above script to give you an idea what the final outcome looks like.

TUC:GR8?MHYP
6I9G2B]LG3H2
U8OO:^7DE;cb
93RW4]>VI`L9
[V?W^;M1E4Oc

Here are few another related blog post on the similar subject:

If you know any other way to generate a random password, please share it and I will publish with due credit.

Reference: Pinal Dave (http://blog.SQLAuthority.com)

SQL Random, SQL Scripts, SQL Server, SQL Server Security
Previous Post
How to Check Edition Specific Features Enabled In SQL Server? – Interview Question of the Week #180
Next Post
How to Convert Hex Windows Error Codes to the Meaningful Error Message – 0x80040002 and 0x80040005 and others? – Interview Question of the Week #182

Related Posts

Leave a Reply