2012-06-28 85 views
1

這是我的更新語句,它完美地工作。如果表1和表2包含相同的序列號,則表1更新爲是,如果不更新,則更新爲否。在更新語句中嵌入select語句

UPDATE dbo.table1 
SET [Match] = CASE WHEN dbo.table2.[Serial Number] IS NOT NULL 
THEN 'yes' ELSE 'no' END 
FROM dbo.table1 LEFT OUTER JOIN dbo.table2 
    ON dbo.table2.[Serial Number] = dbo.table1.[Serial Number] 
AND dbo.table1.[Date] = 'JAN11' AND 
     dbo.table1.[Install] = 'new' AND 
     dbo.table2.[Date] = 'JAN11' AND 
     dbo.table2.[Install] = 'new' 

的問題,目前一切都在表1原位缺口被稱爲也更新了沒有所以我想要做的是首先調用select語句......像這樣

select * from table1 where [Date] = 'JAN11' AND [Install] = 'new' 

並將其嵌套在更新中,以便相關列僅更新爲否或是...

回答

14
UPDATE t1 
    SET [Match] = CASE WHEN t2.[Serial Number] IS NOT NULL 
    THEN 'yes' ELSE 'no' END 
FROM dbo.table1 AS t1 
LEFT OUTER JOIN dbo.table2 AS t2 
    ON t1.[Serial Number] = t2.[Serial Number] 
    AND t1.[Date] = t2.[Date] 
    AND t1.[Install] = t2.[Install] 
WHERE t1.[Date] = 'JAN11' 
    AND t1.[Install] = 'new';