SQL Server User Defined Function (UDF) for Generating Random Passwords

Here is an example how to make random password generator using user-defined function (UDF) in SQL Server.

First create a view that calls the RAND() function, because RAND function cannot be called directly from a user-defined function:

CREATE VIEW [dbo].[Get_RAND]
AS
SELECT RAND() AS MyRAND

Use this code to create user-defined function for generating complex random passwords of desired length (@pass_len), from the list of valid password characters (@ValidChar):

CREATE FUNCTION ufn_RandomPassword (@pass_len AS int)
RETURNS nvarchar(400)
BEGIN
DECLARE @password nvarchar(400)
DECLARE @ValidChar AS nvarchar(400)
SET @ValidChar = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~!@#$%^&*()_-+={}[]\|:;"<>,.?/'
DECLARE @counter int
SET @counter = 0
SET @password = ''
WHILE @counter < @pass_len BEGIN SELECT @password = @password + SUBSTRING(@ValidChar, (SELECT CONVERT(int, (LEN(@ValidChar) * MyRAND + 1)) FROM Get_RAND), 1) SET @counter += 1 END RETURN @password END GO

To use the function to get a 10 characters long password:

SELECT dbo.ufn_RandomPassword (10)

Here is a sample output:

10_characters_password

To use the function to get a 12 characters long password:

SELECT dbo.ufn_RandomPassword (12)

Here is a sample output:

12_characters_password

Read related blog post:
SQL Server Stored Procedure for Generating Complex Random Passwords

You can use our online Password Generator to generate complex random passwords:
Password Generator

If the post helped you, please share it:
Pin It

1 comment to SQL Server User Defined Function (UDF) for Generating Random Passwords

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">