Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 them. I tried this:

select column1, column2, floor(rand() * 10000) as column3  from table1 

Which kinda works, but the problem is that this query returns the same random number on every row. It's a different number each time you run the query, but it doesn't vary from row to row. How can I do this and get a new random number for each row?

like image 811
Joshua Carmody Avatar asked Sep 18 '08 17:09

Joshua Carmody


1 Answers

I realize this is an older post... but you don't need a view.

select column1, column2,    ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 10000 as column3  from table1 
like image 56
Timothy Khouri Avatar answered Nov 16 '22 21:11

Timothy Khouri