更新表从 SQL Server 2022 中的三个连接表获取值

问题描述 投票:0回答:1

我试图对表 INVOICE.field1 = RECEIPT.field1 运行更新,但是 INVOICE 和 RECEIPT 之间没有直接关系,而是通过包含与这两个表的关系的 PURCHASE 表进行更新。我正在使用 SQL Server 2022。

以下选项不起作用:

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

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

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')
sql-server t-sql sql-update multiple-tables sql-server-2022
1个回答
0
投票

我更喜欢使用以下语法:

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

通过这种方式,您可以根据需要构建联接,并且只需在更新开始时引用正确的表即可。

© www.soinside.com 2019 - 2024. All rights reserved.