简体   繁体   中英

UPDATE random row from another table SQL Server 2014

I tried to do an UPDATE statement with a random row from another table. I know this question has been asked before ( here ), but it doesn't seem to work for me.

I should update each row with a different value from the other table. In my case it only gets one random row from a table and puts that in every row.

UPDATE dbo.TABLE_CHARGE
SET COLRW_STREET = 
     (SELECT TOP 1 COLRW_STREET FROM CHIEF_PreProduction.dbo.TABLE_FAKESTREET
     ORDER BY ABS(CHECKSUM(NewId())%250))

Thanks in advance!

I took a liberty to assume that you have ID field in your TABLE_CHARGE table. This is probably not the most efficient way, but seems to work:

WITH random_values as
(
SELECT t.id, t.COLRW_STREET, t.random_street FROM (
  SELECT c.id, c.COLRW_STREET, 
   f.COLRW_STREET as random_street, ROW_NUMBER() OVER (partition by c.id ORDER BY ABS(CHECKSUM(NewId())%250)) rn
  FROM table_charge c, TABLE_FAKESTREET f) t
  WHERE t.rn = 1
)
UPDATE random_values SET COLRW_STREET = random_street;

SQL Fiddle demo

Your original code did not work because when yo do ... SET x = (SELECT TOP 1 ..) database does OUTER JOIN of your target table with one TOP row, which means that one single row is applied to all rows in your target table. Hence you have same value in all rows.

Following query demonstrates what is happening in the UPDATE :

SELECT * FROM 
    TABLE_CHARGE tc,
     (SELECT TOP 1 COLRW_STREET as random_street FROM TABLE_FAKESTREET
         ORDER BY ABS(CHECKSUM(NewId())%250)) t

My solution gets all fake records ordered randomly for each record in target table and only selects the first one per ID.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM