2

When I use this query, it assigns every row to the same value. Is there anyway to make this not happen?

UPDATE Team
SET GroupID = CAST(RAND() * 4 AS INT)

TO CLARIFY: This is to be used with Netbeans to assign group numbers to teams.

+----+----------+-------------+------------------+---------+
| ID |  School  | TeamCaptain |      Email       | GroupID |
+----+----------+-------------+------------------+---------+
|  1 | School 1 | John        | email@email.com  | NULL    |
|  2 | School 2 | James       | email2@email.com | NULL    |
+----+----------+-------------+------------------+---------+

SandySands method works. However, is there any way to make it so that the same number can't appear more than 4 times?

2 Answers2

0

Try this, it's working for me.

UPDATE Team
SET GroupID = CAST(RAND(CHECKSUM(NEWID()))*10000000 AS INT)
WHERE GroupID IN (SELECT GroupID FROM Team
GROUP BY GroupID
HAVING COUNT(GroupID)<4)

This code ensures random values are assigned for all GroupId's in Team table AND no GroupID would have an occurrence of more than 4

SanyTiger
  • 666
  • 1
  • 8
  • 23
0

One way to do it is:

SELECT *, ABS(CAST(NEWID() AS binary(6)) %4) + 1 randomNumber
FROM TEAM

Used in an update:

UPDATE Team
SET GroupID = ABS(CAST(NEWID() AS binary(6)) %4) + 1 randomNumber

Solution taken from:

SQL SERVER – Random Number Generator Script – SQL Query

Note: The distribution is pretty good however there are the occasional peaks.

Tanner
  • 22,205
  • 9
  • 65
  • 83