SQL Clone
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

t-sql random string generator

Note: originally published in our old blog on December 2008.

This is a simple stored procedure that you can use to generate a random string. You can use it as a random password generator and for other purposes. It is very simple so I won't bore you with unnecessary explanations but if you do happen to have any questions feel free to post them here.

CREATE PROCEDURE [dbo].[usp_GenerateRandomString]
@sLength tinyint = 10,
@randomString varchar(50) OUTPUT
DECLARE @counter tinyint
DECLARE @nextChar char(1)
SET @counter = 1
SET @randomString = ''

WHILE @counter <= @sLength
SELECT @nextChar = CHAR(ROUND(RAND() * 93 + 33, 0))
IF ASCII(@nextChar) not in (34, 39, 40, 41, 44, 46, 96, 58, 59)
SELECT @randomString = @randomString + @nextChar
SET @counter = @counter + 1

xSQL blog

Endi Zhupani is a university graduate from Tirana with a degree in Information Systems. He currently works for Pragmatic Software, a company in Tirana that develops transaction and operation management systems as web applications. Throughout his entire development experience, Q&A and blog posts from other developers have saved my day more times that he can count, so he thought he’d start giving back by writing about my work and solutions he has come up with for some interesting problems.


Leave a comment on the original post [blog.xsql.com, opens in a new window]

Loading comments...