用儲存過程實現隨機生成N條記錄 原創

2021-04-13 03:00:03 字數 1485 閱讀 3955

/*測試表為:office(officeid int,o_name varchar(50),o_type tinyint)

write by zhubian qq195986181

*/create procedure dbo.randselect

(@number int --輸入引數(要生成的記錄條數))as

declare @tablestring varchar(20)

create table #1(officeid int,o_name varchar(50),o_type tinyint) --存放隨機生成的記錄(臨時表)

create table #2(rand_num int) --存入已放入#1的記錄的officeid(實現不生成相同的兩條記錄)

declare @officeid int , @o_name varchar(50) , @o_type tinyint , @randnum int , @rowcount int , @i int

select @rowcount = (select count(*) from office)

if @number<@rowcount

begin

set @i = @number   --要求隨機生成的記錄條數(輸入引數)

endelse

begin

set @i = @rowcount

enddeclare c cursor scroll  for select * from office

open c

while(@i>0) 

begin

declare @tempoid int--記錄生成生的隨機數是否重複

set @randnum = rand()*@rowcount+1

set @tempoid = (select count(*) from #2 where rand_num = @randnum)

while( @tempoid <>0 )

begin

set @randnum = rand()*@rowcount+1

set @tempoid = (select count(*) from #2 where rand_num = @randnum)

endfetch absolute @randnum from c into @officeid,@o_name,@o_type

insert into #1 values(@officeid,@o_name,@o_type)

insert into #2 values(@randnum)

set @i = @i-1

endclose c

deallocate c

select * from #1

drop table #1

drop table #2

go--exec randselect @number=150

--drop procedure dbo.randselect

oracle隨機查詢n條記錄

從table name表中隨機查詢3條記錄,如下 select from select from table name where 條件 order by trunc dbms random.value 1,7 temp where rownum 3 附 一 oracle trunc 函式的用法 t...

access excel取隨機n條記錄

乙個簡單的問題被我搞複雜了,都不行,我一直在想著怎麼用 access 的語法來實現,也就是在 access 上面做文章,回來的時候,靈機一動,既然是 sql就應該可以用 sql的語法來實現,何況我對 access 不很熟原來的語句 select top 100 from openrowset mic...

SQL Server 隨機取n條記錄

客戶要搞個 程式。生個隨機數往記錄上對感覺太麻煩,想讓記錄隨機排序。select from table order by rand rand需要個種子,幫助例項 select rand datepart mm,getdate 100000 datepart ss,getdate 1000 datep...