0

我想为从 select 语句返回的每一行生成一个“随机”整数,其中随机 int 每天仅更改一次(凌晨 4 点之前和之后)。

例子

declare @Date datetime

set @Date = dateadd(dd, 8, GETDATE())

declare @DateNumber int

set @DateNumber = LEFT(CONVERT(VARCHAR(8), @Date, 112),10) 
+ cast(CASE WHEN DATEPART(hh, @Date) > 4 THEN 1 ELSE 0 END as varchar(1))

declare @Customers table (Id int, Customer varchar(150), OrderNo int)

insert into @Customers (Id, Customer) values (1, 'Cust A'),  (2, 'Cust B'), 

(3, 'Cust C'), (4, 'Cust D'), (5, 'Cust E'), (6, 'Cust F'), (7, 'Cust G'), (8, 'Cust' H'), (9, 'Cust I')

-- my 1st attempt which doesnt work

update @Customers set OrderNo = rand(@DateNumber) / rand(Id) * 100

select * from 
@Customers order by OrderNo 

结果的顺序应该保持不变,直到我更改@Date顶部 set 语句中的 dd 值。

有任何想法吗?这可能吗?(除了通过 SQL 作业每天计算)


HABO 推荐的更新解决方案

declare @Date datetime = dateadd(hh, 36, GETDATE())

declare @DateNumber int = LEFT(CONVERT(VARCHAR(8), @Date, 112),10) + 
cast(CASE WHEN DATEPART(hh, @Date) > 4 THEN 1 ELSE 0 END as varchar(1))

declare @Customers table (Id int, Customer varchar(150), OrderNo int)

insert into @Customers (Id, Customer) values (1, 'Cust A'),  (2, 'Cust B'), 
(3, 'Cust C'), (4, 'Cust D'), (5, 'Cust E'), (6, 'Cust F'), 
(7, 'Cust G'), (8, 'Cust H'), (9, 'Cust I')

declare @ThrowAway as Float = Rand(@DateNumber)

declare @ID int

set @ID = (select min(ID) from @Customers)

while @ID is not null

begin

    update @Customers set OrderNo = Floor(Rand() * 100) + 1 where ID = @ID


    set @ID = (select min(ID) from @Customers where ID > @ID) 

end 


select * from @Customers order by OrderNo 
4

1 回答 1

1

当您向其提供种子时RAND( Seed ),它将返回相同的结果。如果您在UPDATE查询之前使用种子值,它将初始化序列。此后只需使用RAND()没有参数。就像是:

declare @ThrowAway as Float = Rand( @DateNumber )
update @Customers
  set OrderNo = Floor( Rand() * 100 ) + 1

请记住,随机值包括重复值。

于 2013-05-27T02:33:42.040 回答