How do I generate random number for each row in a TSQL Select?

前端 未结 19 946
逝去的感伤
逝去的感伤 2020-11-22 07:03

I need a different random number for each row in my table. The following seemingly obvious code uses the same random value for each row.

SELECT table_name,          


        
相关标签:
19条回答
  • 2020-11-22 07:41

    Random number generation between 1000 and 9999 inclusive:

    FLOOR(RAND(CHECKSUM(NEWID()))*(9999-1000+1)+1000)
    

    "+1" - to include upper bound values(9999 for previous example)

    0 讨论(0)
  • 2020-11-22 07:41

    It's as easy as:

    DECLARE @rv FLOAT;
    SELECT @rv = rand();
    

    And this will put a random number between 0-99 into a table:

    CREATE TABLE R
    (
        Number int
    )
    
    DECLARE @rv FLOAT;
    SELECT @rv = rand();
    
    INSERT INTO dbo.R
    (Number)
        values((@rv * 100));
    
    SELECT * FROM R
    
    0 讨论(0)
  • 2020-11-22 07:43
    select round(rand(checksum(newid()))*(10)+20,2)
    

    Here the random number will come in between 20 and 30. round will give two decimal place maximum.

    If you want negative numbers you can do it with

    select round(rand(checksum(newid()))*(10)-60,2)
    

    Then the min value will be -60 and max will be -50.

    0 讨论(0)
  • 2020-11-22 07:44
    select ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) as [Randomizer]
    

    has always worked for me

    0 讨论(0)
  • 2020-11-22 07:46

    You would need to call RAND() for each row. Here is a good example

    https://web.archive.org/web/20090216200320/http://dotnet.org.za/calmyourself/archive/2007/04/13/sql-rand-trap-same-value-per-row.aspx

    0 讨论(0)
  • 2020-11-22 07:47

    Answering the old question, but this answer has not been provided previously, and hopefully this will be useful for someone finding this results through a search engine.

    With SQL Server 2008, a new function has been introduced, CRYPT_GEN_RANDOM(8), which uses CryptoAPI to produce a cryptographically strong random number, returned as VARBINARY(8000). Here's the documentation page: https://docs.microsoft.com/en-us/sql/t-sql/functions/crypt-gen-random-transact-sql

    So to get a random number, you can simply call the function and cast it to the necessary type:

    select CAST(CRYPT_GEN_RANDOM(8) AS bigint)
    

    or to get a float between -1 and +1, you could do something like this:

    select CAST(CRYPT_GEN_RANDOM(8) AS bigint) % 1000000000 / 1000000000.0
    
    0 讨论(0)
提交回复
热议问题