表中的每一行都需要一个不同的随机数。下面的代码对每一行使用相同的随机值。
SELECT table_name, RAND() magic_number
FROM information_schema.tables
我想从中得到一个INT或FLOAT。接下来,我将使用这个随机数从已知日期创建一个随机日期偏移量,例如从开始日期的1-14天偏移量。
这是为Microsoft SQL Server 2000。
表中的每一行都需要一个不同的随机数。下面的代码对每一行使用相同的随机值。
SELECT table_name, RAND() magic_number
FROM information_schema.tables
我想从中得到一个INT或FLOAT。接下来,我将使用这个随机数从已知日期创建一个随机日期偏移量,例如从开始日期的1-14天偏移量。
这是为Microsoft SQL Server 2000。
当前回答
试试这个:
SELECT RAND(convert(varbinary, newid()))*(b-a)+a magic_number
a是较小的数,b是较大的数
其他回答
我有时对所选“答案”的问题是,分布并不总是均匀的。如果您需要在大量行中随机分布1 - 14,您可以这样做(我的数据库有511个表,所以这是可行的。如果你的行数比你的随机数跨度少,这就行不通了):
SELECT table_name, ntile(14) over(order by newId()) randomNumber
FROM information_schema.tables
这种方法与普通随机解相反因为它保持了数字的顺序并使另一列随机化。
请记住,我的数据库中有511个表(这只与我们从information_schema中选择的b/c相关)。如果我把前面的查询放到临时表#X中,然后对结果数据运行这个查询:
select randomNumber, count(*) ct from #X
group by randomNumber
我得到这个结果,显示我的随机数非常均匀地分布在许多行中:
您是否在每一行中都有一个整数值,可以作为种子传递给RAND函数?
要得到1到14之间的整数,我相信这是可行的:
FLOOR( RAND(<yourseed>) * 14) + 1
如果你想生成一个1到14之间的随机数。
SELECT CONVERT(int, RAND() * (14 - 1) + 1)
OR
SELECT ABS(CHECKSUM(NewId())) % (14 -1) + 1
当在单个批处理中多次调用rand()时,将返回相同的数字。
我建议使用convert(varbinary,newid())作为种子参数:
SELECT table_name, 1.0 + floor(14 * RAND(convert(varbinary, newid()))) magic_number
FROM information_schema.tables
Newid()保证每次调用都会返回不同的值,即使是在同一个批处理中,因此将它作为种子将提示rand()每次给出不同的值。
编辑以获得从1到14的随机整数。
如果你需要保存你的种子,以便它每次生成“相同”的随机数据,你可以做以下事情:
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