Search

Thursday, October 20, 2011

create random string Function


SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 
GO 
Create View RandomString as select rand() as r
GO
CREATE Function [dbo].[GenerateRandomString] 
(
@StringLength AS smallint 

RETURNS varchar(100) 
AS 
BEGIN 
DECLARE @RandomString varchar(100) 
DECLARE @characters varchar(100) 
DECLARE @count int SET @characters = '' 
-- Load 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 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 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 @RandomString = '' 
WHILE @count < @StringLength 
BEGIN 
SET @RandomString = @RandomString + SUBSTRING(@characters,CAST((SELECT r FROM RandomString)*LEN(@characters) as int)+1,1) 
SET @count = @count + 1 
END 
RETURN @RandomString 
END
GO


SELECT dbo.GenerateRandomString(12)
GO

No comments:

Post a Comment