表中的每一行都需要一个不同的随机数。下面的代码对每一行使用相同的随机值。

SELECT table_name, RAND() magic_number 
FROM information_schema.tables 

我想从中得到一个INT或FLOAT。接下来,我将使用这个随机数从已知日期创建一个随机日期偏移量,例如从开始日期的1-14天偏移量。

这是为Microsoft SQL Server 2000。


当前回答

使用newid ()

select newid()

或者可能是这个

select binary_checksum(newid())

其他回答

使用newid ()

select newid()

或者可能是这个

select binary_checksum(newid())
select ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) as [Randomizer]

一直对我有效吗

如果你需要保存你的种子,以便它每次生成“相同”的随机数据,你可以做以下事情:

1. 创建一个返回select rand()的视图

if object_id('cr_sample_randView') is not null
begin
    drop view cr_sample_randView
end
go

create view cr_sample_randView
as
select rand() as random_number
go

2. 创建一个从视图中选择值的UDF。

if object_id('cr_sample_fnPerRowRand') is not null
begin
    drop function cr_sample_fnPerRowRand
end
go

create function cr_sample_fnPerRowRand()
returns float
as
begin
    declare @returnValue float
    select @returnValue = random_number from cr_sample_randView
    return @returnValue
end
go

3.在选择数据之前,输入rand()函数,然后在选择语句中使用UDF。

select rand(200);   -- see the rand() function
with cte(id) as
(select row_number() over(order by object_id) from sys.all_objects)
select 
    id,
    dbo.cr_sample_fnPerRowRand()
from cte
where id <= 1000    -- limit the results to 1000 random numbers

如果你不需要它是一个整数,而是任何随机的唯一标识符,你可以使用newid()

SELECT table_name, newid() magic_number 
FROM information_schema.tables

生成1000到9999之间的随机数,包括:

FLOOR(RAND(CHECKSUM(NEWID()))*(9999-1000+1)+1000)

"+1" -包含上限值(上例为9999)