Sunday, February 19, 2012

generate a random int to add to a record

I need to generate a random whole number between 0 and 999 to add to
add to every record in a table. The number needs to be different for
each record in the table.

How would I do this all within TSQL?the procedure of mystery man produces random numbers but they can
appear more than once which should not happen. So it would be
necessary to create a new number, check if it exists, if not use it,
else create a new random number, ... can become a timeconsuming
problem if you try this with numbers between 1 and 999 and you have
more than 999 records in your database :-))
If you only need it to do a random read, try this:

select * from myTable order by newid()

this will show you the records every time in another order.

hth,
Helmut

"Mystery Man" <PromisedOyster@.hotmail.com> schrieb im Newsbeitrag
news:87c81238.0307030244.627bf1@.posting.google.com ...
> Have a look at the Rand function.
> Here is a possible example
> declare @.counter int
> SET @.counter = 1
> WHILE @.counter < 1000
> begin
> print convert(int,substring(convert(varchar(8), RAND(@.counter)),6,3))
> SET @.counter = @.counter + 1
> end

No comments:

Post a Comment