博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
sql 两个数字范围取随机数
阅读量:570 次
发布时间:2019-03-10

本文共 821 字,大约阅读时间需要 2 分钟。

常用到通过两个数字之间获取随机数,C#中有内置方法,数据库中没有。以前有找到过一个方法,是通过数据库自定义函数实现,但是找不到了,今天自己写了个,记录下来备用!

 

代码如下:

if 
exists(
select 
* 
from sys.objects 
where name 
= 
'
f_random
')
    
drop 
function f_random
go
/*
两个数之间获取随机数
*/
create 
function f_random
(
    
@min_num 
int,
    
@max_num 
int
)
returns 
int
as
begin
    
declare 
@basicnumber 
decimal(
18,
9)    
--
基数
    
declare 
@randnumber 
decimal(
18,
9
--
随机数
    
if 
@max_num 
<= 
10
        
set 
@basicnumber 
= 
10
    
else 
if 
@max_num 
<= 
100
        
set 
@basicnumber 
= 
100
    
else 
if 
@max_num 
<= 
1000
        
set 
@basicnumber 
= 
1000
    
else 
if 
@max_num 
<= 
10000
        
set 
@basicnumber 
= 
10000
    
while 
1 
= 
1
    
begin
        
select 
@randnumber 
= randvalue 
from vRandom
        
set 
@randnumber 
= 
@randnumber 
* 
@basicnumber
        
if 
@randnumber 
>= 
@min_num 
and 
@randnumber 
< 
@max_num
            
break
        
else
            
continue
    
end
    
return 
cast(
@randnumber 
as 
int)
end
go

使用方法:

select dbo.f_random(1,100) as randnum    

一定要加dbo!

 

 

转载地址:http://nqzvz.baihongyu.com/

你可能感兴趣的文章