Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update table with random record in update statment in SQL Server?

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

like image 601
chobo Avatar asked Oct 25 '12 20:10

chobo


2 Answers

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
like image 136
Lamak Avatar answered Oct 28 '22 18:10

Lamak


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.

like image 43
Gordon Linoff Avatar answered Oct 28 '22 17:10

Gordon Linoff