设为首页 加入收藏

TOP

SQLSever:如何在select中的每一行产生不同的随机数?
2014-11-23 22:13:44 来源: 作者: 【 】 浏览:10
Tags: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
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇应对黑客攻击SQLSERVER数据库一例 下一篇SQLServer2008杀死数据库连接

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: