博客
关于我
sql 两个数字范围取随机数
阅读量:572 次
发布时间: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/

你可能感兴趣的文章
MySQL 的mysql_secure_installation安全脚本执行过程介绍
查看>>
MySQL 的Rename Table语句
查看>>
MySQL 的全局锁、表锁和行锁
查看>>
mysql 的存储引擎介绍
查看>>
MySQL 的存储引擎有哪些?为什么常用InnoDB?
查看>>
Mysql 知识回顾总结-索引
查看>>
Mysql 笔记
查看>>
MySQL 精选 60 道面试题(含答案)
查看>>
mysql 索引
查看>>
MySQL 索引失效的 15 种场景!
查看>>
MySQL 索引深入解析及优化策略
查看>>
MySQL 索引的面试题总结
查看>>
mysql 索引类型以及创建
查看>>
MySQL 索引连环问题,你能答对几个?
查看>>
Mysql 索引问题集锦
查看>>
Mysql 纵表转换为横表
查看>>
mysql 编译安装 window篇
查看>>
mysql 网络目录_联机目录数据库
查看>>
MySQL 聚簇索引&&二级索引&&辅助索引
查看>>
Mysql 脏页 脏读 脏数据
查看>>