2

The SQL server documentation says that calling the rand function with the same seed produces the same value and that the subsequent calls to rand() will produce values according to the seed first provided.

SELECT RAND(100), RAND(), RAND()

BUT, what about something like:

update dbo.product set price= rand();

This always produced the same value for all rows. What is the "academic" explanation for this behavior?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Diego Quirós
  • 898
  • 1
  • 14
  • 28

1 Answers1

0

Since RAND does not run for each row, you can use ABS(CHECKSUM(NEWID())) to accomplish the random values for each row.

DECLARE @Min INT = 10, @Max INT = 20
UPDATE dbo.product SET price = ABS(CHECKSUM(NEWID())) % (@Max - @Min) + @Min
Jason W
  • 13,026
  • 3
  • 31
  • 62