SQL Server 中隨機函式應用舉例

2021-09-21 12:05:14 字數 1018 閱讀 1955

最近工作中要隨機生成一些資料,基本上全是通過rand()函式來完成。下面以幾個例子做下簡單說明。

1.生成年齡

思路:年齡一般為0-100歲,只要以當時日期為基準,用dateadd函式加上乙個0-100的隨機數即可。

**:declare @nl int,@csrq date

set @nl=cast((rand()*1000000) as int)%(100*365)

set @csrq=dateadd(dd,-@nl,getdate())

print @csrq

2.從資料表中隨機取100條資料

思路:在生成資料的時候遇到其中有一張表中只有乙個地區的資料,這樣生成出來的地圖其他地區全為空。所以準備從原表中直接取出部分資料庫做修改後再寫回資料庫中。

**:declare @a int 

set @a=cast(rand()* 100000 as int)%9 

select top 3 *,@a as a into #temp from test 

order by newid() 

delete from #temp where a=8 

update #temp 

set name=name+cast(@a as varchar(20))

insert into test(id,name) 

select id,name from #temp 

drop table #temp

3.隨機生成50-100條資料

思路:在按地區寫入資料的時候,如果都寫入100條資料,則出來的效果不會理想,所以我希望按地區寫入50-100條資料。用rand()函式生成乙個最大值,然後用while迴圈生成資料。

declare @i int 

set @i=cast(rand()*100000 as int)%50+1 

while @i<100 

begin

end另:rand()函式在同一事務中生成的值唯一,所以如果要在寫入不同的值,要用迴圈做逐條寫入。

SQL Server中隨機函式的應用

select from student order by newid select top n from student order by newid 這裡的n代表隨機顯示的記錄數 注 newid 返回的是uniqueidentifier型別的唯一值。newid 每次產生的值都不一樣,那麼根據這樣的...

OpenGL中gluLookAt 函式的應用

今天寫了乙個自己的camera 宣告如下 include vector3.h ifndef camera h define camera h namespace learnopengl endif 其中setcamera 成員函式用來指定攝像機所處位置,觀察點位置和向上的向量,定義如下 void l...

UFT中ChildObjects 函式的應用

qtp 中childobjects 函式的應用 childobjects 函式主要用於頁面中同一型別物件的批量操作,減少 量 如在 中的 寶貝中有很多寶貝要進行批量下架,可以用以下方法得到 使用方法詳解 1 首先對要操作的物件建立乙個description物件 set mydescription d...