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

前端 未结 19 947
逝去的感伤
逝去的感伤 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:48
    RAND(CHECKSUM(NEWID()))
    

    The above will generate a (pseudo-) random number between 0 and 1, exclusive. If used in a select, because the seed value changes for each row, it will generate a new random number for each row (it is not guaranteed to generate a unique number per row however).

    Example when combined with an upper limit of 10 (produces numbers 1 - 10):

    CAST(RAND(CHECKSUM(NEWID())) * 10 as INT) + 1
    

    Transact-SQL Documentation:

    1. CAST(): https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
    2. RAND(): http://msdn.microsoft.com/en-us/library/ms177610.aspx
    3. CHECKSUM(): http://msdn.microsoft.com/en-us/library/ms189788.aspx
    4. NEWID(): https://docs.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql
    0 讨论(0)
提交回复
热议问题