问题
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