How can I update rows at random?
Assuming your Names table has a primary key field called Id, this will nullify the nickname in a random 50 percent of the rows:
update dbo.Names set Nickname = null where Id in
(
select top 50 percent id from dbo.Names order by NEWID()
)
RAND()
persists within a query.
SELECT RAND()
FROM names
will give you a set of equal numbers.
You need to do something like this:
WITH q AS
(
SELECT *,
ABS(CHECKSUM(NEWID())) % 2 AS r
FROM names
)
UPDATE q
SET nickname = NULL
WHERE r = 0
RandNumber
is a function. Functions in SQL must output the same result every time for the same input, unless underlying database data has changed. This is the mathematical definition of a function (as opposed to how a normal programming language treats a "function," which is more of a function-like construct).
Since the result of your function should never change during an update statement (which is an atomic operation) the query plan compiler for your query only calls RandNumber
once and then caches the result.
You may be able to get away with just referencing RAND
directly in your query, but if that still doesn't work, you'll have to do this iteratively in a stored procedure.