Roy Harvey (SQL Server MVP) (roy_harvey@snet.net) writes:
Quote:
What version of SQL Server are you running? It makes a BIG
difference. Or, as your name ( php_mysql_beginer911) suggests are you
using MySQL but posting questions to a Microsoft SQL Server group?
>
Here is an answer that will only work in SQL Server, but will work in
any version.
>
UPDATE TheTable
SET age = RAND() * 10000
FROM (SELECT name, age, count(*) as dups, min(id) as keepme
FROM TheTable
GROUP BY name, age
HAVING count(*) 1) as X
WHERE TheTable.name = X.name
AND TheTable.age = X.age
AND TheTable.id <X.keepme
Nah, there are a couple of problems. First, in php_mysql_beginer911's
sample data, the name was unique, so that condition should be removed.
Next, rand() is evaluated once, so all rows get the same new age. This
can be addressed with instead using checksum(newid()). We still need
one more thing trough, a loop that runs the update until @@rowcount is
0. That is, since new numbers are random, we may get new duplicates. So
WHILE 1 = 1
BEGIN
UPDATE TheTable
SET age = checksum(newid())
FROM (SELECT age, count(*) as dups, min(id) as keepme
FROM TheTable
GROUP BY age
HAVING count(*) 1) as X
WHERE TheTable.age = X.age
AND TheTable.id <X.keepme
IF @@rowcont = 0 BREAK
END
--
Erland Sommarskog, SQL Server MVP,
esquel@sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx