Solved

Generating a random string in Sql server

Posted on 2014-11-25
3
193 Views
Last Modified: 2014-11-26
If I have 300 users in my database, and I need to assign each one a random Id,
how can I do this using SQL server. I don't want to use GUIDs because I think that is kind of over kill.

I would like the ID to be 4 characters long. I can query the database to find out if the id already exists, and if it does, I just run the random id sql code again, until I get a unique id.
0
Comment
Question by:brgdotnet
  • 2
3 Comments
 
LVL 65

Assisted Solution

by:Jim Horn
Jim Horn earned 354 total points
ID: 40466077
Probably a more graceful way to pull this off, but this works
Declare @max smallint = 1, @min smallint = 26

SELECT 
   CHAR(((@max + 1) - @min) * Rand() + @min + 64) + 
   CHAR(((@max + 1) - @min) * Rand() + @min + 64) + 
   CHAR(((@max + 1) - @min) * Rand() + @min + 64) + 
   CHAR(((@max + 1) - @min) * Rand() + @min + 64)

Open in new window


btw Check out my article an article:  T-SQL recipe to create a million sample people that has a wompload of SQL Server random number/random name features.
0
 
LVL 15

Assisted Solution

by:Vikas Garg
Vikas Garg earned 146 total points
ID: 40466085
Hi,

You can use this along with your query

SELECT format(CAST(RAND() * 10000 AS int),'0000') AS RandomNumber , username from Usertable
0
 
LVL 65

Accepted Solution

by:
Jim Horn earned 354 total points
ID: 40466734
btw if you have some time to play with this, you could create a table with string values 'spring', 'summer', 'winter', 'fall', then mimic the article code I have to make your passwords a random string value and a couple of numbers.  

Will be easier to remember spring23 then UKEW.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question