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

前端 未结 19 953
逝去的感伤
逝去的感伤 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: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
    

提交回复
热议问题