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

我是研究僧i 提交于 2021-01-29 11:12:04

问题


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
);

回答1:


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


来源:https://stackoverflow.com/questions/65662593/update-multiple-records-in-table-by-using-a-reference-table-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!