2009-12-10 68 views
12

只有在另一個表中存在匹配行的情況下,對於主表中當前列爲空的所有行,我需要將表上的某個字段更新爲true。在另一個表中存在匹配行時更新行

這是我所想達到的描述:

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語句?

回答

9

你是爲期不遠了......

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]) 
2

你缺少的東西是「從」條款,這是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] 
    ) 
4

您需要使用您的更新聯接:

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 
4

這似乎有悖常理,但你需要EST在From子句中填寫表別名,但在更新子句中使用該別名...

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) 
相關問題