Solved

# SQL random values

Posted on 2007-10-07
1,053 Views
Hello all,

I am looking for the SQL statement that will update all the rows of my field
with random values between 30-100.
Thus, each record should be filled with a random value, but should not be
the same in all the records. It is ok if some records have the same values though.

Any ideas?
0
Question by:nectarios777

LVL 142

Expert Comment

random generic formula:
Round(((@Upper - @Lower -1) * Rand() + @Lower), 0)

Round(((289) * Rand() + 10), 0)

0

LVL 1

Author Comment

Hello angelIII,

here is what I'm using:

update tbTable
set totalratings =
Round(((289) * Rand() + 10), 0)

The problem is that all records are being updated with the same value.
I want each record to have a different value.
0

LVL 142

Expert Comment

update tbTable
set totalratings = ( select top 1
Round(((289) * Rand() + 10), 0)  from tbltable order by newid() )
0

LVL 1

Author Comment

Hello,

still the same problem
0

LVL 142

Expert Comment

0

LVL 1

Author Comment

AngelIII, have you got any idea how to make it return integers >1 rather than decimals?
0

LVL 142

Accepted Solution

simply combine the code in the link above with the formula posted first + casting:

create view wrapped_rand_view
as
select rand( ) as random_value
go
create function wrapped_rand()
returns int
as
begin
declare @f float
declare @r int
set @f = (select random_value from wrapped_rand_view)
set @r = Round(((289) * @f + 10), 0)
return @r
end
go
update t set d = dbo.wrapped_rand()

0

## Featured Post

Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be \$37.1B.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.