Sunday, February 15, 2009

T-SQL - Random password generator

After creating a database in SQL server I created an
Application Role: DBname->Security->Roles->Application Roles

Then when I selected to create the script of that Application Role
in a new query Editor window, I found a part of code to generate a
random password, with some changes, I decided to write it here. To
run it, you can copy paste the code as a query in query editor window
of SSMS and execute the line of codes to see the output which is a
32 character length random generated password.

DECLARE @iCntr AS int
DECLARE @rndmPwd AS nvarchar(32)
DECLARE @rndm AS float

SET @iCntr = 0
SET @rndmPwd = N''

-- @@CPU_BUSY Shows the No. of busy CPU milliseconds
-- since the SQL Server instance was last started.
--
-- @@IDLE Displays the total idle time of the SQL
-- Server instance in milliseconds, since the
-- instance was last

SET @rndm =
   rand(
   ( @@CPU_BUSY % 100 ) +
   ( (@@IDLE % 100) * 100 ) +
   ( DATEPART(ss, GETDATE()) * 10000 ) +
   (
      (cast(DATEPART(ms,GETDATE()) as int) % 100) *
      1000000
   )
   )

WHILE @iCntr < 32
BEGIN
   SET @rndmPwd =
   @rndmPwd +
   char( ( cast( (@rndm * 83) as int ) + 43 ) )

   SET @iCntr = @iCntr + 1
   SET @rndm = rand()
END
PRINT @rndmPwd

Share/Bookmark

No comments: