我需要更新表上的字段,只有当另一个表中存在匹配的行时才更新,对于主表中当前列为空的所有行。
这是我想要实现的目标的描述:
UPDATE [LenqReloaded].[dbo].[Enquiry] A
SET [ResponseLetterSent] = 1
WHERE [ResponseLetterSent] IS NULL
AND EXISTS
(
SELECT * FROM [LenqReloaded].[dbo].[Attachment] B
WHERE A.[EnquiryID] = B.[EnquiryID]
)
这在语法上并不正确。
我无法通过IF EXISTS ...语句对其进行编码,因为我没有[EnquiryID]而没有从表中读取数据。
我应该如何设置UPDATE语句的格式?
答案 0 :(得分:10)
你离我不远......
UPDATE A
SET A.[ResponseLetterSent] = 1
FROM [LenqReloaded].[dbo].[Enquiry] A
WHERE A.[ResponseLetterSent] IS NULL
AND EXISTS ( SELECT * FROM [LenqReloaded].[dbo].[Attachment] B WHERE A.[EnquiryID] = B.[EnquiryID] )
答案 1 :(得分:5)
您需要在更新中使用联接:
UPDATE [LenqReloaded].[dbo].[Enquiry] SET [ResponseLetterSent] = 1
FROM [LenqReloaded].[dbo].[Enquiry] A
join [LenqReloaded].[dbo].[Attachment] B on A.[EnquiryID] = B.[EnquiryID]
WHERE A.[ResponseLetterSent] IS NULL
答案 2 :(得分:4)
这似乎违反直觉,但您需要在From子句中建立表别名,但在Update Clause中使用该别名...
Update E Set
ResponseLetterSent = 1
From LenqReloaded.dbo.Enquiry E
Where ResponseLetterSent Is Null
And Exists (Select * From LenqReloaded.dbo.Attachment
Where EnquiryID = E.EnquiryID)
答案 3 :(得分:2)
你缺少的是'from'子句,这是一个t-sql扩展 - 它是为更新的表分配别名的唯一方法
update [lenqreloaded].[dbo].[enquiry]
set [responselettersent] = 1
from [lenqreloaded].[dbo].[enquiry] a
where [responselettersent] is null
and exists (
select *
from [lenqreloaded].[dbo].[attachment] b
where a.[enquiryid] = b.[enquiryid]
)