您的位置:首页 > 数据库

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

2017-06-07 18:06 176 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: