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

前端 未结 19 949
逝去的感伤
逝去的感伤 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 07:24

    The Rand() function will generate the same random number, if used in a table SELECT query. Same applies if you use a seed to the Rand function. An alternative way to do it, is using this:

    SELECT ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) AS [RandomNumber]
    

    Got the information from here, which explains the problem very well.

提交回复
热议问题