Monday, September 18, 2006

Populating a Column with Random Values

Suppose you have a table:

create table t(i int, d float)
insert into t values(1, 0.0)
insert into t values(2, 0.0)
insert into t values(3, 0.0)
insert into t values(4, 0.0)

Suppose you want to populate d with random values:

update t set d = rand()

Unfortunately it will assign one and the same value to all the rows:

select * from t

i d----------- ----------------------
1 0.430774201738828
2 0.430774201738828
3 0.430774201738828
4 0.430774201738828
(4 row(s) affected)

Here is the right way to do it:

create view wrapped_rand_view
select rand( ) as random_value
create function wrapped_rand()
returns float
declare @f float
set @f = (select random_value from wrapped_rand_view)
return @f
update t set d = dbo.wrapped_rand()

select * from t

i d
----------- ----------------------
1 0.665934939858962
2 0.99919527046644
3 0.844039650356367
4 0.146401486624627
(4 row(s) affected)


At 8:39 AM, Anonymous Anonymous said...

Nice! Just what I needed

At 6:29 AM, Anonymous Anonymous said...

it is the best solution.

At 2:48 AM, Anonymous Anonymous said...

Thanks for the tip, really helpfull!
I needed to update not with random values, but with random id's from specific table, so here how i changed the view:

create view wrapped_rand_view
SELECT TOP 1 ProjectId as random_value FROM dbo.Project ORDER BY NEWID()

Hope somebody will find it usefull.

Еще раз спасибо! :-)

At 12:18 AM, Anonymous Anonymous said...

awesome! thanks!

At 11:54 AM, Anonymous Anonymous said...

Order By Newid()? I didn't think GUIDs could be sorted without first casting them to a character form.


Post a Comment

<< Home