Multiple random values in SQL Server 2005

爱⌒轻易说出口 提交于 2020-01-15 05:55:08

问题


I need to generate multiple random values under SQL Server 2005 and somehow this simply wont work

with Random(Value) as
(
    select rand() Value
        union all
    select rand() from Random

)select top 10 * from Random

Whats the preffered workaround?


回答1:


have you tries something like this (found at http://weblogs.sqlteam.com ) :

CREATE VIEW vRandNumber
AS
SELECT RAND() as RandNumber
GO

create a function

CREATE FUNCTION RandNumber()
RETURNS float
AS
  BEGIN
     RETURN (SELECT RandNumber FROM vRandNumber)
  END
GO

then you can call it in your selects as normal Select dbo.RandNumber() , * from myTable

or from their comments:

select RAND(CAST(NEWID() AS BINARY(6))), * from myTable



回答2:


I'm currently using this:

with Random(Value) as
(
    select rand(checksum(newid())) Value
        union all
    select rand(checksum(newid())) from Random  
)select top 10 * from Random

but that seems overly hackish :S Why doesnt rand get reevaluated in the first version?



来源:https://stackoverflow.com/questions/183124/multiple-random-values-in-sql-server-2005

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!