需要 rand() 和 cursorr 来生成不同的数字

Need rand() and cursorr to generate different number

我知道这段代码会为每一行生成相同的数字 因为更新语句是针对整列的,循环只是覆盖了最后一步,但是我如何为每一行生成不同的数字并且我没有主键和任何类型的键?

declare @origCost float
declare table_cursor cursor for 
select cost from [dbo].[x]where cost  is not null
open table_cursor;
Fetch next from table_cursor into @origCost

while @@FETCH_STATUS = 0
BEGIN
 update [dbo].[x]

 set cost=@origCost* round(rand()+rand(),2) where  cost is not null
 Fetch Next from table_cursor into @origCost
END;
CLOSE table_cursor;
DEALLOCATE table_cursor; 

使用下面的查询..

WITH cte_data 
AS (
SELECT cost,(cost*round(rand()+rand(),2)origCost
FROM [dbo].[x])
UPDATE a
SET a.cost=a.origCost
FROM cte_data a 

如果您需要不同的数字进行计算,请使用以下脚本

WITH cte_data 
AS (
SELECT cost,ROW_NUMBER()OVER(ORDER BY cost)*(cost)origCost
FROM [dbo].[x])
UPDATE a
SET a.cost=a.origCost
FROM cte_data a 

要获得 0..2 以内的随机小数,请使用 CAST (ABS(CHECKSUM(NewId())) % 200 /100. AS DECIMAL(3,2)) 而不是 round(rand()+rand(),2)

declare @origCost float
declare table_cursor cursor for 
select cost from [dbo].[x]where cost  is not null
open table_cursor;
Fetch next from table_cursor into @origCost

while @@FETCH_STATUS = 0
BEGIN
 update [dbo].[x]

 set cost=@origCost* round(rand()+rand(),2) where  cost is not null
 Fetch Next from table_cursor into @origCost
END;
CLOSE table_cursor;
DEALLOCATE table_cursor; 

声明一个变量.. xxxxxxxxx 值.. + randome no.... 对于每个陈述 +1;