方法一
步驟1:
隨機數的SQL函數為rand():
select rand(); 而rand()生成的是0-1之間的小數。
如:0.644341629331498
想要得到10之間的隨機整數:
Select round(rand()*9+1,0)
n到m之間的隨機整數(n<m):
Select round(rand()*(m-n)+n,0)
cast的作用是類型轉換,將隨機數轉化為float(6),得到的結果就是我們需要的隨機數了:
Select cast(round(rand()*(m-n)+n,0) as float(6))
步驟2:
更新每一條數據的某一字段
update [test].[dbo].[table]
set [table.rand] = cast(rand()*(999999-100000)+100000 as float(6))
這種想法是有多天真啊。這樣更新下來只能導致這個字段變成相同的一個隨機值。
如:
777
777
777
中獎啦!呵呵。
步驟3:
-- 更新 my_table 的 test_rand 字段
--1、聲明游標 指定有表指定的是數據庫的哪一個字段.(在這里只能選擇作為主鍵的id)
DECLARE @user_id varchar(36) --可寫多個
DECLARE user_extension_cursor CURSOR
FOR
SELECT id --可寫多個
FROM [test].[dbo].[table] --可寫條件
--2、需要用FETCH來獲取游標
OPEN user_extension_cursor;
FETCH NEXT FROM user_extension_cursor
INTO @user_id --可寫多個
--3、循環更新字段的值
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE [test].[dbo].[table]
SET [table].[rand] = cast(rand()*(m-n)+n as float(6))
WHERE id = @user_id --可寫多個
FETCH NEXT FROM user_extension_cursor
INTO @user_id --可寫多個
END
CLOSE user_extension_cursor;
DEALLOCATE user_extension_cursor;
---
方法二
update [test].[dbo].[table]
set [table.rand] = cast(rand(checksum(newid()))*(999999-100000)+100000 as float(6))
select newid() 如:57C26BA5-8304-4877-B5D4-256C80428B94
select rand() 如:0.029051900701824
select checksum(500) 如:500
select checksum(newid()) 如:35757911
select rand(checksum(newid())) 如:0.657911662715189
select rand(checksum(newid()))*(999999-100000)+100000 如:881621.124049528
select cast(rand(checksum(newid()))*(999999-100000)+100000 as float(6)) 如:609545.7
非原創