关于网友提出的“ sql如何获取不重复的随机数”问题疑问,本网通过在网上对“ sql如何获取不重复的随机数”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题: sql如何获取不重复的随机数描述:
sql随机数
问题:在存储过程中,我需要获取5个随机数(1--30之间),然后把这5个随机数保存起来,作为下边的sql的参数,如何获取这5个随机数并保存呀?例子:班级一共提供30中活动,每个人必须参加5中不同的活动,然后把每个人的选择结果插入一个表中,请写出存储过程?
解决方案1:
declare @t table(x int)
while((select count(1) from @t where x<>0)<>5
or exists(select x from @t group by x having count(1)>1))
begin
delete from @t
insert into @t(x)
select cast(rand(checksum(newid()))*30 as int) union all
select cast(rand(checksum(newid()))*30 as int) union all
select cast(rand(checksum(newid()))*30 as int) union all
select cast(rand(checksum(newid()))*30 as int) union all
select cast(rand(checksum(newid()))*30 as int)
end
select x from @t order by x
/*
x
-----------
3
4
7
8
13
(5 row(s) affected)
*/