Tuesday, 23 June 2015

SP to Generate Random Password in SQL (with upper,lower case characters,digits ,punctuation characters)


GO
/****** Object:  StoredProcedure [dbo].[USP_GenerateRandomPassword]    Script Date: 6/23/2015 12:52:26 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Gokuldas.Palapatta
-- Create date: 19th feb 20114
--/* Description: Should contain both upper and lower case characters
--(e.g., a-z, A-Z), digits and punctuation characters as well as
-- letters e.g., 0-9, !@#$%^&*()_+|~-=\`{}[]:";'<>?,./) and should be at least
--eight (alphanumeric with one special and one upper case) characters long */
--declare @x varchar(10)
--execute USP_GenerateRandomPassword @Password=@x output
--select @x
-- =============================================
CREATE  PROCEDURE [dbo].[USP_GenerateRandomPassword] (@Password varchar(10)='' OUTPUT)

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @vRandomNum_Var varchar(10)
DECLARE @SPL VARCHAR(2)
SET @vRandomNum_Var = ''

Declare  @TempTable TABLE(
                         ID int,
                         Charachter char(20))
INSERT INTO @TempTable (ID, Charachter)  SELECT 35, '#'
INSERT INTO @TempTable (ID, Charachter)  SELECT 64, '@'
INSERT INTO @TempTable (ID, Charachter)  SELECT 36, '$'
INSERT INTO @TempTable (ID, Charachter)  SELECT 37, '%'
INSERT INTO @TempTable (ID, Charachter)  SELECT 94, '^'
INSERT INTO @TempTable (ID, Charachter)  SELECT 38, '&'
INSERT INTO @TempTable (ID, Charachter)  SELECT 42, '*'
INSERT INTO @TempTable (ID, Charachter)  SELECT 95, '_'
INSERT INTO @TempTable (ID, Charachter)  SELECT 45, '-'

  SET @SPL = (SELECT top 1 Charachter FROM @TempTable
ORDER BY NEWID())



SET @vRandomNum_Var = (select top 1 cast((Abs(Checksum(NewId()))%10) as varchar(1)) +
       char(ascii('a')+(Abs(Checksum(NewId()))%25)) +
       char(ascii('A')+(Abs(Checksum(NewId()))%25)) +
  @SPL +
       left(newid(),4)
FROM @TempTable)
SET @vRandomNum_Var = REPLACE(@vRandomNum_Var,' ','')
    SELECT @Password = @vRandomNum_Var

END




No comments:

Post a Comment