博客
关于我
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 用 limit 为什么会影响性能?
查看>>
MySQL 用 limit 为什么会影响性能?有什么优化方案?
查看>>
MySQL 用户权限管理:授权、撤销、密码更新和用户删除(图文解析)
查看>>
mysql 用户管理和权限设置
查看>>
MySQL 的 varchar 水真的太深了!
查看>>
mysql 的GROUP_CONCAT函数的使用(group_by 如何显示分组之前的数据)
查看>>
MySQL 的instr函数
查看>>
MySQL 的mysql_secure_installation安全脚本执行过程介绍
查看>>
MySQL 的Rename Table语句
查看>>
MySQL 的全局锁、表锁和行锁
查看>>
mysql 的存储引擎介绍
查看>>
MySQL 的存储引擎有哪些?为什么常用InnoDB?
查看>>
Mysql 知识回顾总结-索引
查看>>
Mysql 笔记
查看>>
MySQL 精选 60 道面试题(含答案)
查看>>
mysql 索引
查看>>
MySQL 索引失效的 15 种场景!
查看>>
MySQL 索引深入解析及优化策略
查看>>
MySQL 索引的面试题总结
查看>>