欢迎来到.net学习网

欢迎联系站长一起更新本网站!QQ:879621940

您当前所在位置:首页 » Sql随手笔记 » 正文

热门阅读

在sql server数据库中取指定范围内的随机整数示例

创建时间:2012年04月18日 15:33  阅读次数:(10834)
分享到:
大家应该都知道sql server中Rand()函数用法了,好吧,如果你不知道,我们可以解释一下:
Rand()函数:返回一个介于0和1之间的随机float值

但这个函数并没有提供参数让我们设置返回的随机数的范围,比如我只想返回一个大于或等于1但同时又要小于或等于100的整数。现在我们做一个自定义函数,用于返回一个指定最大值与最小值内的随机整数。该自定义函数还是需要用到Rand系统函数,但因为在函数中是不能够使用Rand函数的,如果有使用,会报以下的错误:
在函数内的 'rand' 中对带副作用的或依赖于时间的运算符的使用无效

为了解决该问题,我们先创建一个视图V_Rand,用于读取一个随机数,视图代码如下:
CREATE VIEW View_Rand  
AS  
SELECT RAND() AS RandValue

有了该视图,我们就开始创建我们需要的函数了,sql如下:
CREATE FUNCTION [dbo].[udf_GetRandomInteger]
(
@MinValue int = null,
@MaxValue int = null
)
RETURNS int
AS
/*
函数名称:udf_GetRandomInteger
功能简述:取随机整数
相关对象:无
参数:@MinValue 最小值
@MaxValue 最大值
*/
BEGIN

declare @RandomValue float
declare @ReturnValue int

while(1=1)
begin
--从随机数视图中获取一个随机值(因为函数中不能直接使用rand(),所以用V_Rand视图代替)
select @RandomValue = RandValue from V_Rand
--根据最大最小值获取随机整数
if @MinValue is not null and @MaxValue is not null
begin
select @ReturnValue = ceiling(@RandomValue * @MaxValue)
if  @ReturnValue  >= @MinValue and @ReturnValue <= @MaxValue
begin
break
end
end
else if @MinValue is not null and @MaxValue is null
begin
select @ReturnValue = ceiling(@RandomValue * @MinValue)
if  @ReturnValue  >= @MinValue
begin
break
end
end
else if @MinValue is null and @MaxValue is not null
begin
select @ReturnValue = ceiling(@RandomValue * @MaxValue)
if  @ReturnValue <= @MaxValue
begin
break
end
end
else if @MinValue is null and @MaxValue is null
begin
select @ReturnValue = convert(int,substring(convert(varchar(20),@RandomValue),3,20))
break
end
end

return @ReturnValue

END

上面的函数也有用到了ceiling()系统函数,该函数的作用就返回一个总是大于或等于指定的numeric值的整数。比如:ceiling(1.1),会返回2,celing(2),也会返回2,它不会对参数进行四舍五入的运算。

好了,函数创建完毕,我们可以开始测试该函数了,执行以下sql
select dbo.udf_GetRandomInteger(1,100)

是不是总是返回一个大于或等于1且小于或等于100的整数呢。
来源:.net学习网
说明:所有来源为 .net学习网的文章均为原创,如有转载,请在转载处标注本页地址,谢谢!
【编辑:Wyf

打赏

取消

感谢您的支持,我会做的更好!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

最新评论

共有评论0条
  • 暂无任何评论,请留下您对本文章的看法,共同参入讨论!
发表评论:
留言人:
内  容:
请输入问题 63+9=? 的结果(结果是:72)
结  果: