日期:2014-05-18  浏览次数:20482 次

ASP/SQL让一个列能在规定的数字范围内递增或随机生成不重复的数字
ASP/SQL让一个列能在规定的数字范围内递增或随机生成不重复的数字

如范围是100-1000之间

id     |   name     |     number   |
1           abc               101
2           aaa               266
3           dsf               999
4           sdf               500
5           dfd               328

最好是在一定范围内随机生成,如果不行,递增也可以。是在SQL执行,还是在程序中执行。怎么做?


------解决方案--------------------
SQL code
'参数说明:c_floor随机数的下限,c_upper随机数的上限,num要生成随机数的个数
'注意:c_floor<c_upper而且都不能为负数,num<=c_upper-c_floor,否则会出现死循环
'调用 call random(1,40,10) 随机产生10个1-40之间的数字

  Function random(c_floor,c_upper,num)
  Dim a(),temp,flag,i,j
  
  Redim a(num)  '重定义数组
  
  i=1

  Do while i<cint(num)+1

  '生成随机数
   randomize()
   temp=cint(int((cint(c_upper)*rnd())+cint(c_floor)))
   flag=0
  
  '判断生成的随机数时候已经存在,是则重新生成
   for j=1 to ubound(a)
    if cint(temp)=cint(a(j)) then
     flag=1
     Exit for
    End if
   next

  '将生成的随机数存放到数组中
  if flag=0 then
   a(i)=temp
   Response.write a(i) & "<br>"
   i=i+1
  End if

  loop

  random=a  '返回一个数组对象
  End function

------解决方案--------------------
SQL code

rand()   返回从 0 到 1 之间的随机 float 值。


select ceiling(rand()*1000)

------解决方案--------------------
SQL code

create table t(id int ,name varchar(3),number int)
insert t select
1,           'abc'    ,           101 union all select 
2 ,          'aaa'   ,            266 union all select
3  ,         'dsf'  ,             999 union all select
4   ,        'sdf' ,              500 union all select
5    ,       'dfd',               328 

alter table  t add nn int

declare @n int,@m int
set @n=1
set @m=(select max(id)from  t)

while @n<=@m
begin
    update  t
    set nn= ceiling(rand()*1000)
    where id=@n
    
    set @n=@n+1
end
go 

select * from t
id          name number      nn
----------- ---- ----------- -----------
1           abc  101         988
2           aaa  266         952
3           dsf  999         419
4           sdf  500         197
5           dfd  328         167

(5 行受影响)

drop table t

------解决方案--------------------
随机和区间的简单 递增不重复的需要做特别处理
写个大概的
<%
Function RndNumber(MaxNum,MinNum)
Randomize
RndNumber=int((MaxNum-MinNum+1)*rnd+MinNum)
RndNumber=RndNumber
End Function
%>
如果需要小数把int去掉
递增和重复问题只能判断数据表中现有数据了
用select查吧
------解决方案--------------------
探讨
ASP/SQL让一个列能在规定的数字范围内递增或随机生成不重复的数字

如范围是100-1000之间

id     |   name     |     number   |
1           abc               101
2           aaa               266
3           dsf               999
4           sdf               500
5           dfd               328

最好是在一定范围内随机生成,如果不行,递增也可以。是在SQL执行,还是在程序中执行。怎么做?


------解决方案--------------------