2

I am using SQL Server 2005, please tell me how can I get 6 digits (unique numeric which should be random) value for every row in table.

I have a field in table in which I need 6 digit numeric value (random and unique).

Please help me to do this.

5
  • a 6 digit value is not going to be very unique now is it? Commented May 17, 2010 at 6:45
  • actually wants a 6 digit numeric value in random and unique for every row in table Commented May 17, 2010 at 6:47
  • actually it will be a "EXTENSION" to phone number.. so cant take more than that Commented May 17, 2010 at 6:48
  • Why are you generating a unique, random number for an extension? This seems like an unrealistic thing to be doing, even assuming you are using this purely as test data. Without knowing more about the system you're developing I can't say for sure, but I'd want to be absolutely sure that both random and unique are required Commented May 17, 2010 at 7:53
  • actually we will provide a phone extension number to each user who will register to out site. Commented May 17, 2010 at 9:42

1 Answer 1

6
SELECT ABS(CHECKSUM(NEWID())) % 999999

for a phone number:

SELECT RIGHT('000000' + CAST(ABS(CHECKSUM(NEWID())) % 999999 AS varchar(6)), 6)

NEWID is about as random as you can get in SQL Server.

However, if you want unique, you may as well start at 000000 and go to 999999. Any random generator will hit the birthday problem.

You can have unique or random that are reliable, but not both reliably

Sign up to request clarification or add additional context in comments.

3 Comments

@Mitch Wheat: I was extending my answer as you commented
SELECT LEFT('000000' + CAST(ABS(CHECKSUM(NEWID())) % 999999 AS varchar(6)), 6) is always giving me 000000, no other results
@Rajesh Rolen- DotNet Developer: my mistake, should be RIGHT. Sorry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.