How do I return random numbers as a column in SQL Server 2005?

后端 未结 12 789
误落风尘
误落风尘 2020-12-03 01:34

I\'m running a SQL query on SQL Server 2005, and in addition to 2 columns being queried from the database, I\'d also like to return 1 column of random numbers along with the

12条回答
  •  暖寄归人
    2020-12-03 02:13

    This snippet seems to provide a reasonable substitute for rand() in that it returns a float between 0.0 and 1.0. It uses only the last 3 bytes provided by newid() so total randomness may be slightly different than the conversion to VARBINARY then INT then modding from the recommended answer. Have not had a chance to test relative performance but seems fast enough (and random enough) for my purposes.

    SELECT CAST(SubString(CONVERT(binary(16), newid()), 14, 3) AS INT) / 16777216.0 AS R
    

提交回复
热议问题