資料庫給欄位新增隨機數
阿新 • • 發佈:2022-04-20
一.當資料表有唯一自增ID
Declare @CurentRecord int,@BeginNum int, @EndNum int, @TotalCount int,@Value int
set @BeginNum=1 -- 起止時間設定隨機數範圍,我想要1~3的隨機數,所以起始數為1
set @EndNum=4 -- 終止數為4,不包含4
set @TotalCount=5 -- 生成隨機數的個數
set @CurentRecord=1 -- 標誌位
While @CurentRecord<=@TotalCount
Begin
set @Value= @BeginNum+(@EndNum - @BeginNum)*rand()
-- select @Value
update [testTable] set [level] = @Value where [ID] = @CurentRecord
set @CurentRecord=@CurentRecord+1
End
二.資料表沒有自增ID
如果操作的資料表沒有唯一自增ID時,在上邊程式碼update中where [ID] = @CurentRecord顯然是行不通的,在sql server中,我們可以通過row_number()over()來給表生成一個隱式編號,然後通過這個編號去操作:
DECLARE @startnum int,@endnum int,@count int,@flag int, @value int
set @startnum = 1 -- 生成1~5的隨機數
set @endnum = 6
set @count = 1000
set @flag = 1
while @flag <= @count
Begin
Set @value = @startnum + (@endnum - @startnum)*RAND()
update [t1] set t1.level = @value from t1, (SELECT top 1000 ROW_NUMBER()over(order by authorname) num,[packageDate],[authorName] FROM [t1]) B
where t1.packageDate = B.packageDate and t1.authorName = B.authorName and B.num = @flag
Set @flag = @flag + 1
End