常用到通过两个数字之间获取随机数,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
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!