如何在SQL中随机生成一个Integer

时间:2021-08-26 20:31:21

As the question suggests.

正如问题所示。

I need to randomly generate an Integer at the end of my SQL query. It is supposed to be part of a code that I have to create from existing variables.

我需要在SQL查询结束时随机生成一个Integer。它应该是我必须从现有变量创建的代码的一部分。

SELECT LEFT(Var1,2) & RIGHT(Var2,1) & RND
FROM MyTable;

The method I used here generates a number that is a decimal like 0,2895625 at the end of the code. I need it to generate a whole Integer.

我在这里使用的方法生成一个十进制数,如代码末尾的0,2895625。我需要它来生成一个整数。

Thanks Again!

再次感谢!

1 个解决方案

#1


2  

DECLARE @maxval TINYINT, @minval TINYINT
select @maxval=24,@minval=5

SELECT CAST(((@maxval + 1) - @minval) *
    RAND(CHECKSUM(NEWID())) + @minval AS TINYINT)

Use this. set @maxval and @minval according to your need.

用这个。根据您的需要设置@maxval和@minval。

Or try this.

或试试这个。

SELECT CAST(RAND() * 1000000 AS INT)

Or you can try this.

或者你可以试试这个。

 Declare @Rnd INT;

   set @Rnd = CAST(RAND() * 1000000 AS INT)
    SELECT LEFT(Var1,2) & RIGHT(Var2,1) & @Rnd
    FROM MyTable;

or

要么

Declare @Rnd INT;

     set @Rnd = ABS(CHECKSUM(NewId())) % 10000 
        SELECT LEFT(Var1,2) & RIGHT(Var2,1) & @Rnd
        FROM MyTable;

#1


2  

DECLARE @maxval TINYINT, @minval TINYINT
select @maxval=24,@minval=5

SELECT CAST(((@maxval + 1) - @minval) *
    RAND(CHECKSUM(NEWID())) + @minval AS TINYINT)

Use this. set @maxval and @minval according to your need.

用这个。根据您的需要设置@maxval和@minval。

Or try this.

或试试这个。

SELECT CAST(RAND() * 1000000 AS INT)

Or you can try this.

或者你可以试试这个。

 Declare @Rnd INT;

   set @Rnd = CAST(RAND() * 1000000 AS INT)
    SELECT LEFT(Var1,2) & RIGHT(Var2,1) & @Rnd
    FROM MyTable;

or

要么

Declare @Rnd INT;

     set @Rnd = ABS(CHECKSUM(NewId())) % 10000 
        SELECT LEFT(Var1,2) & RIGHT(Var2,1) & @Rnd
        FROM MyTable;