如何在SQL SERVER中生成范围为X倍的随机数

如何在SQL SERVER中生成范围为X倍的随机数,sql,sql-server,tsql,Sql,Sql Server,Tsql,我想生成一个随机数X倍的范围。我尝试创建一个函数: CREATE FUNCTION Random_Number (@Times INT, @Upper BIGINT,@Lower BIGINT, @randomvalue numeric(18,10)) RETURNS INT AS BEGIN DECLARE @Random BIGINT DECLARE @Row INT SET @Row = 1 WHILE @Row <= @Times BE

我想生成一个随机数X倍的范围。我尝试创建一个函数:

CREATE FUNCTION Random_Number (@Times INT, @Upper BIGINT,@Lower BIGINT, @randomvalue numeric(18,10))
RETURNS INT
AS
BEGIN
    DECLARE @Random BIGINT
    DECLARE @Row INT

    SET @Row = 1

    WHILE  @Row <= @Times
    BEGIN
        SELECT @Random = ROUND(((@Upper - @Lower -1) * @randomvalue + @Lower), 0)
        SET @Row = @Row + 1
    END
    RETURN @Random
END
GO


select dbo.Random_Number(5,2002100001,2002100010,RAND())
我希望得到以下结果:

#1 2002100003
#2 2002100000
#3 2002100009
#4 2002100006
#5 2002100007

有可能吗?

您可以使用递归方法:

with cte as (
     select 2002100001 as st, 2002100010 as ed
     union all
     select c.st + 1, c.ed
     from cte c
     where c.st < c.ed
)
select top (5) st
from cte
order by newid(); 

也许递归cte?像一个符咒一样工作!:-这正是我想要的。谢谢大家!@莱托。这不允许重复。这可能是一件好事,也可能不是一件好事,但您不能在问题中指定不替换项。
with cte as (
     select 2002100001 as st, 2002100010 as ed
     union all
     select c.st + 1, c.ed
     from cte c
     where c.st < c.ed
)
select top (5) st
from cte
order by newid();