SQLSever: 如何在select中的每一行產生不同的隨機數?,sqlseverselect
select 的隨機函數有點假, 也許是因為它是基於時間來的吧, 同一select中由於時間無法錯開導致產生的隨機數都是一樣的, 如何做到讓不同的行擁有不同的隨機數呢?
下面以產生某個月的隨機日期來樣本吧。
--建立最小為1 最大為31 的視圖if object_id('view_rand_int31') is not nullbegindrop 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 nullbegindrop function dbo.Fun_GetRandDayendgoCREATE FUNCTION dbo.Fun_GetRandDay(@max INT)returns intas begindeclare @r intselect @r = [r] from view_rand_int31while @r>@maxbeginselect @r = [r] from view_rand_int31if @r<=@maxbeginbreak;endendreturn @rendgo--實驗select條件下實現多條記錄同時取隨機數--插入實驗資料行declare @t table(rowNum int identity, [yearMonth] nvarchar(20))declare @i int,@imax intselect @i=1,@imax =28while @i<=@imaxbegininsert 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