select 的随机函数有点假, 也许是因为它是基于时间来的吧, 同一select中由于时间无法错开导致产生的随机数都是一样的, 如何做到让不同的行拥有不同的随机数呢?
下面以产生某个月的随机日期来示例吧。
--创建最小为1 最大为31 的视图if object_id('view_rand_int31') is not nullbegin drop view view_rand_int31endgocreate view view_rand_int31as select cast(ceiling(rand() * 31) as int) as [r]go--创建日期(天)的随机函数if object_id('dbo.Fun_GetRandDay') is not nullbegin drop function dbo.Fun_GetRandDayendgoCREATE FUNCTION dbo.Fun_GetRandDay(@max INT)returns intas 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 @rendgo--试验select条件下实现多条记录同时取随机数--插入试验数据行declare @t table(rowNum int identity, [yearMonth] nvarchar(20))declare @i int,@imax intselect @i=1,@imax =28while @i<=@imaxbegin insert into @t ([yearMonth]) select '2014年2月' set @i=@i+1end--执行查询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