I have two tables. Table 1
has about 80 rows and Table 2
has about 10 million.
I would like to update all the rows in Table 2
with a random row from Table 1
. I don't want the same row for all the rows. Is it possible to update Table 2
and have it randomly select a value for each row it is updating?
This is what I have tried, but it puts the same value in each row.
update member_info_test
set hostessid = (SELECT TOP 1 hostessId FROM hostess_test ORDER BY NEWID())
**Edited
Ok, I think that this is one of the weirdest query that I've wrote, and I think that this is gonna be terrible slow. But give it a shot:
UPDATE A
SET A.hostessid = B.hostessId
FROM member_info_test A
CROSS APPLY (SELECT TOP 1 hostessId
FROM hostess_test
WHERE A.somecolumn = A.somecolumn
ORDER BY NEWID()) B
I think this will work (at least, the with
portion does):
with toupdate as (
select (select top . . . hostessId from hostess_test where mit.hostessId = mit.hostessId order by newid()) as newval,
mit.*
from member_info_test mit
)
update toupdate
set hostessid = newval;
The key to this (and to Lamak's) is the outer correlation in the subquery. This is convincing the optimizer to actually run the query for each row. I don't know why this would work and the other version would not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With