Monday, March 28, 2011

function to create a random string

set ANSI_NULLS ON set QUOTED_IDENTIFIER ON
go
create view RandomHelper as select rand( ) as r
GO
CREATE function [dbo].[CreateRandomString]
(
@passwordLength as smallint
)
RETURNS varchar(100)
AS
Begin
DECLARE @password varchar(100)
declare @characters varchar(100)
declare @count int set @characters = ''
-- 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
-- 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
-- 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
set @count = 0
set @password = ''
while @count < @passwordLength
begin
set @password = @password + SUBSTRING(@characters,CAST((SELECT r FROM RandomHelper)*LEN(@characters) as int)+1,1)
set @count = @count + 1
end
RETURN @password
end
GO

SELECT dbo.CreateRandomString(10)
go

No comments: