且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 SQL 中用随机数填充一列?我在每一行都得到相同的值

更新时间:2021-11-02 22:05:44

代替 rand(),使用 newid(),它为结果.通常的方法是使用校验和的模.请注意,checksum(newid()) 可以产生 -2,147,483,648 并导致 abs() 上的整数溢出,因此我们需要对校验和返回值使用模数,然后再将其转换为绝对值.

Instead of rand(), use newid(), which is recalculated for each row in the result. The usual way is to use the modulo of the checksum. Note that checksum(newid()) can produce -2,147,483,648 and cause integer overflow on abs(), so we need to use modulo on the checksum return value before converting it to absolute value.

UPDATE CattleProds
SET    SheepTherapy = abs(checksum(NewId()) % 10000)
WHERE  SheepTherapy IS NULL

这会生成一个 0 到 9999 之间的随机数.

This generates a random number between 0 and 9999.