Update table getting values from three joining tables

43 Views Asked by At

I was trying to run an update for the table INVOICE.field1 = RECEIPT.field1, however there is no direct relationship between INVOICE and RECEIPT, but by the PURCHASE table that contains relations with both tables. I am using SQL Server 2022.

Below options don't work:

UPDATE INVOICE T1
SET T1.field1 = T3.field1
FROM PURCHASE T2 
INNER JOIN RECEIPT T3 ON T2.field2 = T3.field2 
WHERE T1.field3 = T2.field3 
  AND T1.field1 IN ('x')

or

UPDATE INVOICE T1
JOIN PURCHASE T2 ON T2.field2 = T3.field2 
JOIN RECEIPT T3 ON T1.field3 = T2.field3
SET T1.field1 = T3.field1
WHERE T1.field1 IN ('x')

or

UPDATE INVOICE T1, PURCHASE T2, RECEIPT T3 
SET T1.field1 = T3.field1
WHERE T1.field3 = T2.field3 
  AND T2.field2 = T3.field2
  AND T1.field1 IN ('x')
1

There are 1 best solutions below

3
siggemannen On

I prefer to use the following syntax:

UPDATE t /*alias of the table to update*/
SET someField = t2.someOtherField
FROM TABLE1 t /*the table with the above alias */
INNER JOIN TABLE3 t3 
   ON t3.ID = t.ID
INNER JOIN TABLE2 t2
   ON t2.ID = t3.ANOTHER_ID

This way you can build your joins as needed and just refer to correct table in the beginning of the UPDATE.