如何设置随机数

时间:2016-06-02 12:13:53

标签: sql sql-server

我只是想知道如何设置随机数,使其在1-10之间,不显示小数,如0.744545454? 另外,如何通过执行迭代每个记录,以便每行包含自己的随机数“PlayerWeighting?”

以下是我的存储过程:

CREATE PROCEDURE [dbo].[Player_CreateWholeTeam]
    @TeamID INT

AS
SET NOCOUNT ON
BEGIN
DECLARE @FirstName VARCHAR(25)
        DECLARE @Surname VARCHAR(25)
        DECLARE @PlayerWeighting TINYINT

        SELECT @FirstName = TeamName  
        FROM dbo.Team 
        WHERE TeamID = @TeamID

        SELECT @Surname = 'Player' + cast(NumberID AS VARCHAR (10)) 
        FROM dbo.Team CROSS JOIN dbo.Number 
        WHERE TeamID = @TeamID 
        ORDER BY TeamID, NumberId

        SELECT @PlayerWeighting = RAND(1-10)
        FROM dbo.Player

    INSERT INTO dbo.Player (FirstName, Surname, PlayerWeighting, TeamID)
    VALUES (@FirstName, @Surname, @PlayerWeighting, @TeamID)


END

3 个答案:

答案 0 :(得分:3)

这是生成随机数的简单代码:

DECLARE @Random INT;
DECLARE @Upper INT;
DECLARE @Lower INT

---- This will create a random number between 1 and 999
SET @Lower = 1 ---- The lowest random number
SET @Upper = 999 ---- The highest random number
SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
SELECT @Random

如果要执行多行,可以将其放入函数中,然后将值设置为该函数的结果。

如果要在用户定义的函数中使用,则必须首先创建视图,因为您不能使用UDF的RAND()函数。

以下是如何执行此过程的示例:

-- View to be used in UDF
CREATE VIEW Get_RAND
AS
SELECT RAND() AS myRand

GO

--Simple UDF to get a random number
CREATE FUNCTION myRandom(@lower INT, @upper INT ) 
    RETURNS int
as

BEGIN

DECLARE @Random INT;

---- This will create a random number between @lower and @upper   
DECLARE @RAND DECIMAL(10,10) = (SELECT myRand FROM Get_RAND)
set @Random = ROUND(((@Upper - @Lower -1) * @RAND + @Lower), 0)
RETURN @Random

END

-- Use of the function
SELECT dbo.myRandom(1, 100)

答案 1 :(得分:2)

您可以使用以下内容:

SELECT CONVERT(INT, (RAND() * 10))

答案 2 :(得分:0)

CREATE PROCEDURE [dbo].[Player_CreateWholeTeam]
    @TeamID INT

AS
SET NOCOUNT ON
BEGIN

INSERT INTO dbo.Player (FirstName, Surname, PlayerWeighting, TeamID)
SELECT  TeamName as Firstname,
        'Player' + cast(NumberID AS VARCHAR (10))  as Surname , 
        FLOOR(RAND(Checksum(NEWID()))*(10-1)+1)     as PlayerWeighting ,
        @TeamID  as TeamID
        FROM dbo.Team  CROSS JOIN dbo.Number 
        WHERE TeamID = @TeamID
End

如上所述替换您的程序代码。我直接从select查询的结果中插入记录。选择查询结合现有查询。选择查询将有助于为每个玩家提供随机玩家加权