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

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



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值