SQLSever: 如何在select中的每一行產生不同的隨機數?,sqlseverselect

來源:互聯網
上載者:User

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



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.