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

时间:2016-08-25 09:59:23

标签: sql sql-server loops cursor

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

DateTimePickerFormat.Custom

3 个答案:

答案 0 :(得分:1)

使用以下查询..

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 

答案 1 :(得分:1)

要在0..2内获得随机小数,请使用CAST (ABS(CHECKSUM(NewId())) % 200 /100. AS DECIMAL(3,2))代替round(rand()+rand(),2)

答案 2 :(得分:0)

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;

相关问题