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

后端 未结 12 781
误落风尘
误落风尘 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 01:55

    I use c# for dealing with random numbers. It's much cleaner. I have a function I use to return a list of random number and a unique key, then I just join the uniqueKey on the row number. Because I use c#, I can easily specify a range within which the random numbers must fall.

    Here are the steps to making the function: http://www.sqlwithcindy.com/2013/04/elegant-random-number-list-in-sql-server.html

    Here is what my query ends up looking like:

    SELECT 
       rowNumber, 
       name, 
       randomNumber
    FROM dbo.tvfRandomNumberList(1,10,100) 
    INNER JOIN (select ROW_NUMBER() over (order by int_id) as 'rowNumber', name from client        
                )as clients
    ON clients.rowNumber = uniqueKey
    
    0 讨论(0)
  • 2020-12-03 02:00

    You need to use a UDF

    first:

    CREATE VIEW vRandNumber
    AS
    SELECT RAND() as RandNumber
    

    second:

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

    test:

    SELECT dbo.RandNumber(), *
    FROM <table>
    

    Above borrowed from Jeff's SQL Server Blog

    0 讨论(0)
  • 2020-12-03 02:00

    You might like to consider generating a UUID instead of a random number using the newid function. These are guaranteed to be unique each time generated whereas there is a significant chance that some duplication will occur with a straightforward random number (and depending on what you're using it for could give you a phenominally hard to debug error at a later point)

    0 讨论(0)
  • 2020-12-03 02:02

    For SQLServer, there are a couple of options.
    1. A while loop to update an empty column with one random number at a time
    2. A .net Assembly that contains a function that returns a random number

    0 讨论(0)
  • 2020-12-03 02:05
    select RAND(CHECKSUM(NEWID()))
    
    0 讨论(0)
  • 2020-12-03 02:05

    According to my testing, the answer above doesn't generate a value of 10000 ever. This probably isn't much of a problem when you are generating a random between 1 and 10000, but the same algorithm between 1 and 5 would be noticable. Add 1 to your mod.

    0 讨论(0)
提交回复
热议问题