SQLSever:如何在select中的每一行产生不同的随机数?

2014-11-23 22:13:44 · 作者: · 浏览: 14

select 的随机函数有点假, 也许是因为它是基于时间来的吧, 同一select中由于时间无法错开导致产生的随机数都是一样的, 如何做到让不同的行拥有不同的随机数呢?

下面以产生某个月的随机日期来示例吧。

--创建最小为1 最大为31 的视图
if object_id('view_rand_int31') is not null
begin
	drop view view_rand_int31
end
go
create view view_rand_int31
as 
	select cast(ceiling(rand() * 31) as int) as [r]
go
--创建日期(天)的随机函数
if object_id('dbo.Fun_GetRandDay') is not null
begin
	drop function dbo.Fun_GetRandDay
end
go
CREATE FUNCTION dbo.Fun_GetRandDay
(
@max INT
)
returns int
as 
begin
	declare @r int
	select @r = [r] from view_rand_int31
	
	while @r>
@max begin select @r = [r] from view_rand_int31 if @r<=@max begin break; end end return @r end go --试验select条件下实现多条记录同时取随机数 --插入试验数据行 declare @t table(rowNum int identity, [yearMonth] nvarchar(20)) declare @i int,@imax int select @i=1,@imax =28 while @i<=@imax begin insert into @t ([yearMonth]) select '2014年2月' set @i=@i+1 end --执行查询 select *, cast( '2014-02-' + cast( dbo.Fun_GetRandDay(28) as varchar(2)) as datetime) as [date], (select cast(ceiling(rand() * 28) as int)) as [r] from @t