表中的每一行都需要一个不同的随机数。下面的代码对每一行使用相同的随机值。
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。
当前回答
您是否在每一行中都有一个整数值,可以作为种子传递给RAND函数?
要得到1到14之间的整数,我相信这是可行的:
FLOOR( RAND(<yourseed>) * 14) + 1
其他回答
如果你需要保存你的种子,以便它每次生成“相同”的随机数据,你可以做以下事情:
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
select round(rand(checksum(newid()))*(10)+20,2)
这里的随机数在20和30之间。 四舍五入最多会给出两位小数点后的数字。
如果你想要负数,你可以这样做
select round(rand(checksum(newid()))*(10)-60,2)
那么最小值将是-60,最大值将是-50。
使用newid ()
select newid()
或者可能是这个
select binary_checksum(newid())
当在单个批处理中多次调用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的随机整数。
试试这个:
SELECT RAND(convert(varbinary, newid()))*(b-a)+a magic_number
a是较小的数,b是较大的数