Monday, 5 February 2018

How to create random password in sql server


CREATE function [dbo].[GenerateRandomNumber]
(
   @PasswordLength as smallint
)

returns varchar(100)

As
   begin
       declare @pwd nvarchar(100)
   declare @characters nvarchar(100)
   declare @count int
   --A to Z  65 - 90
   --a to z  97 - 122
   --0 to 9  48 - 57
 
   set @characters=''
 
   set @count=48
   while(@count <= 57)
   begin
     
     set @characters=@characters + char(@count)
   
     set @count=@count+1
   end
 
   set @count=65
   while(@count <= 90)
   begin
     
   set @characters=@characters + char(@count)
   set @count=@count+1
   end
 
 
       set @count=97
   while(@count <= 122)
   begin
     
   set @characters=@characters + char(@count)
   set @count=@count+1
   end
 
   set @pwd=''
   set @count=0
 
   while(@count < @PasswordLength)
   begin
 
    set @pwd=@pwd+  substring(@characters,convert(int, (select rndResult FROM rndView)*len(@characters)) ,1)
    set @count=@count+1
   end
 

return  @pwd
   end
GO

========================================================================

CREATE VIEW rndView 
AS 
SELECT RAND() rndResult

No comments:

Post a Comment