简体   繁体   中英

Update multiple records in table by using a reference table SQL Server

I am trying to update a table in SQL by using references from two other tables. I need Table C to be updated with the ID of records from Table A but only where a column from Temp Table B exists in Table A

Table A

ID ReferenceNumber
1 123
2 321
3 213
4 413

Temp Table B

ID ExtractedNum
1 213
2 413
3 321
4 123

Expected Results

Table C

TableA_ID TableB_ID
3 1
4 2
2 3
1 4

I've tried a few different queries but none of them work the way I need it to:

UPDATE table_c 
  SET
      table_c.tablea_id = a.id -- int    
FROM table_a a
WHERE table_c.tableb_id =
(
    SELECT t.Id, 
           t.ExtractedNum
    FROM #tempTableB t, 
         table_a a2  
    WHERE t.ExtractedNum = a2.ReferenceNumber
);
UPDATE c
SET c.tablea_id=a.id
FROM tableC c INNER JOIN
tableA a ON a.id=c.tablea_id INNER JOIN
#tempTableB b ON b.ExtractedNum=a.ReferenceNumber

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