CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Raymond Lewallen

Professional Learner

Updated random password or string generator in T-Sql for Sql Server

Here is an updated version of my random string or password generator for T-Sql, made into a stored procedure with some other modifications.

The stored procedure

/***************************************************************************
* Created By: Raymond Lewallen
* Date:  05/16/2005
* Purpose: Generate a random string of given length
*
* Comments: Everything is self-explanatory.  Right now
*  max length is set to 100. So anything between 1
*  and 100 will work for a length.
*
*   If you specify a @charactersToUse,
*  the bit flags get ignored.
*
*   All spaces are stripped from the
*  @charactersToUse.
*
*   Characters can repeat. Will be
*  handled in a future version.
***************************************************************************/

CREATE procedure dbo.GenerateRandomString (
 @useNumbers bit,
 @useLowerCase bit,
 @useUpperCase bit,
 @charactersToUse as varchar(100),
 @passwordLength as smallint,
 @password varchar(100) OUT
)
As
Begin

if @passwordLength <= 0
 raiserror('Cannot generate a random string of zero length.',16,1)

declare @characters varchar(100)
declare @count int

set @characters = ''

if @useNumbers = 1
begin
 -- load up numbers 0 - 9
 set @count = 48
 while @count <=57
 begin
     set @characters = @characters + Cast(CHAR(@count) as char(1))
     set @count = @count + 1
 end
end

if @useLowerCase = 1
begin
 -- load up uppercase letters A - Z
 set @count = 65
 while @count <=90
 begin
     set @characters = @characters + Cast(CHAR(@count) as char(1))
     set @count = @count + 1
 end
end

if @useUpperCase = 1
begin
 -- load up lowercase letters a - z
 set @count = 97
 while @count <=122
 begin
     set @characters = @characters + Cast(CHAR(@count) as char(1))
     set @count = @count + 1
 end
end

set @count = 0
set @password = ''

-- If you specify a character set to use, the bit flags get ignored.
if Len(@charactersToUse) > 0
begin
 while charindex(@charactersToUse,' ') > 0
 begin
  set @charactersToUse = replace(@charactersToUse,' ','')
 end

 if Len(@charactersToUse) = 0
  raiserror('Cannot use an empty character set.',16,1)

 while @count <= @passwordLength
 begin
     set @password = @password + SUBSTRING(@charactersToUse,CAST(ABS(CHECKSUM(NEWID()))*RAND(@count) as int)%LEN(@charactersToUse)+1,1)
     set @count = @count + 1
 end
end
else
begin
 while @count <= @passwordLength
 begin
     set @password = @password + SUBSTRING(@characters,CAST(ABS(CHECKSUM(NEWID()))*RAND(@count) as int)%LEN(@characters)+1,1)
     set @count = @count + 1
 end
end

end
GO

And here are some examples of how to use it.

Use the bit flags - numbers only

declare @a varchar(20)
exec dbo.GenerateRandomString 1,0,0,null,20,@a OUT
print @a

Output: 44509955862560034316


Use the bit flags - entire character set

declare @a varchar(30)
exec dbo.GenerateRandomString 1,1,1,null,30,@a OUT
print @a

Output: bl4Dut6ACchq460u65j2fkYoalrAAN


Use a simple custom character set

declare @a varchar(50)
exec dbo.GenerateRandomString 1,1,1,'Ab',50,@a OUT
print @a

Output: bbbAAAbbbbAbbbAbbAAAbAbbbbbAbAbAbbAAAbAAbAbAbbAbbb


Use a more complex character setdeclare @a varchar(50)
exec dbo.GenerateRandomString 1,1,1,'ManagedCodeRocksMyWorld',50,@a OUT
print @a

Output: nednsndgcdgdnrgolRWRsgooRsdkMoCMRWedyglaknooodrdRd



Comments

RIO - Randektív Informatikai Oldal said:

&lt;ul&gt;
&lt;li&gt;&lt;a target=&quot;_blank&quot; href=&quot;http://desktop.google.com/enterprise&quot;&gt;Google Desktop for Enterprise&lt;/a&gt;
&lt;li&gt;&lt;a target=&quot;_blank&quot; href=&quot;http://www.microsoft.com/downloads/details.aspx?familyid=e315c516-2c2c-4870-a189-d47a5d7ffeb3&amp;#038;displaylang=en&quot;&gt;Excel
# May 18, 2005 8:37 AM

Ben said:

Hey Raymond,

Thanks for the post. Your code came in quite handy and was a great help to me as a newby.

Ben
# June 9, 2005 11:01 AM

Raymond Lewallen said:

Glad to hear it helped you out Ben :)
# June 9, 2005 11:07 AM

Raul said:

Raymond
Thank you to provide your storage procedure..
Raymond I need to generate a ramdom string or number after a user submits its password using a text box on a web page. I believe your store procedure is the right solution in this case.
I also would like to provide back the password using email in case the user forgot his/her password, would you provide me some ideas how can I convert back the ramdom number generated using your store procedure to the original string the user submited.

I will appreciate any help.

Raul
# October 9, 2005 5:13 PM

tribune said:

awesome procedure! cheers
# October 17, 2005 2:03 AM

K Sub said:

Thank you. I found it very useful.
# December 1, 2005 4:15 PM

Wes F. said:

Thank you so much for this great procedure! Exactly what I was looking for!

# September 8, 2006 10:35 AM

Steve said:

Thanks - this is exactly what I was looking for as well.  I did find a bug in the procedure, however.  Whatever length you pass in will return a string 1 character longer.   Bot "while @count <= @passwordLength" lines in the procedure need to simply use "<" since @count is initialized to 0.

# September 20, 2006 9:06 PM

Carl said:

Many thanks, saved lots of work. Flexible yet simple - great!

# October 5, 2006 4:31 AM

komp said:

Excellent work. I appreciate it. It is the one which I am looking for. Saved me lots of time. Thanks

# October 13, 2006 10:02 AM

Chris Beck said:

Thanks - very helpful.

One defect: the application of "use upper case" and "use lower case" are reversed.

# November 10, 2006 5:32 PM

Kathryn said:

Two years on and this post is still a useful resource for people. Thanks for helping to make my task today just that little bit easier!

# May 3, 2007 4:26 AM

Atul said:

This is really perfect for generating a random string.

Thanks a lot for such a nice code.

# June 2, 2007 2:15 AM

Jason said:

Just what I needed. Thanks!

# July 3, 2007 6:42 PM

WebMart Blog » SQL Server 2005 function to create a random string said:

Pingback from  WebMart Blog &raquo; SQL Server 2005 function to create a random string

# October 22, 2007 1:49 PM

Jens Peter Winkler said:

Very useful, thanks a lot. I have used the procedure for obfuscating personal data.

# November 7, 2007 9:51 AM

matt said:

Excellent job with this procedure.. very useful!

I noticed your Upper/Lower case checks are reversed (the if @useUpperCase = 1 generates the lower case characters, etc). Also, the @count should start at 1 instead of zero when creating the string, otherwise the resulting string is 1 character longer than what you requested. It doesn't show up in you examples because the string length is explicit.

# December 11, 2007 1:53 PM

Alex said:

Nice work! Thanks.
# January 30, 2008 4:07 PM

Chandra Mouli said:

Wow... A perfect Procedure for generating Password or PIN.

# April 16, 2008 3:09 AM

Marius Smith said:

Thanks Raymond. I changed your code to allow for the removal of duplicates to use for myself .

Could your verify this is what you meant as my home language is not English?

Below is the code (changes is at the end where you were setting the password?)

CREATE procedure dbo.GenerateRandomString (

@useNumbers bit,

@useLowerCase bit,

@useUpperCase bit,

@charactersToUse as varchar(100),

@passwordLength as smallint,

@password varchar(100) OUT

)

As

Begin

if @passwordLength <= 0

raiserror('Cannot generate a random string of zero length.',16,1)

declare @characters varchar(100)

declare @count int

set @characters = ''

if @useNumbers = 1

begin

-- load up numbers 0 - 9

set @count = 48

while @count <=57

begin

    set @characters = @characters + Cast(CHAR(@count) as char(1))

    set @count = @count + 1

end

end

if @useLowerCase = 1

begin

-- load up uppercase letters A - Z

set @count = 65

while @count <=90

begin

    set @characters = @characters + Cast(CHAR(@count) as char(1))

    set @count = @count + 1

end

end

if @useUpperCase = 1

begin

-- load up lowercase letters a - z

set @count = 97

while @count <=122

begin

    set @characters = @characters + Cast(CHAR(@count) as char(1))

    set @count = @count + 1

end

end

set @count = 0

set @password = ''

-- If you specify a character set to use, the bit flags get ignored.

if Len(@charactersToUse) > 0

begin

while charindex(@charactersToUse,' ') > 0

begin

 set @charactersToUse = replace(@charactersToUse,' ','')

end

if Len(@charactersToUse) = 0

 raiserror('Cannot use an empty character set.',16,1)

while @count <= @passwordLength

begin

    set @password = @password + SUBSTRING(@charactersToUse,CAST(ABS(CHECKSUM(NEWID()))*RAND(@count) as int)%LEN(@charactersToUse)+1,1)

    set @charactersToUse = left(@charactersToUse,CAST(ABS(CHECKSUM(NEWID()))*RAND(@count) as int)%LEN(@charactersToUse)) + right(@charactersToUse,LEN(@charactersToUse)- CAST(ABS(CHECKSUM(NEWID()))*RAND(@count) as int)%LEN(@charactersToUse)+2)

    set @count = @count + 1

end

end

else

begin

while @count <= @passwordLength

begin

    set @password = @password + SUBSTRING(@characters,CAST(ABS(CHECKSUM(NEWID()))*RAND(@count) as int)%LEN(@characters)+1,1)

    set @count = @count + 1

end

end

end

GO

# May 7, 2008 12:03 PM

Ashwini said:

Thanks for giving me nice solution

# September 4, 2008 5:34 AM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About Raymond Lewallen

Working primarily in the public sector during his career, Raymond has designed and built several high profile enterprise level applications for all levels of the government. Raymond now works as a solutions architect for EMC. Raymond is an agile coach, Microsoft MVP C# and also president of the Oklahoma City Developers Group and Oklahoma Agile Developers Group. Raymond spends a lot of his time learning and teaching such things as Test Driven Development, Domain Driven Design, Design Patterns and Extreme Programming practices and principles, to name a few. Raymond is also an advocate of Alt.Net. Raymond is primarily a framework guy, so don't ask him anything about UI :) Check out Devlicio.us!

Our Sponsors