在更新语句中嵌套select语句

时间:2012-06-28 12:22:22

标签: sql sql-server

这是我的更新声明,完美无缺。如果表1和表2包含相同的序列号,则表1更新为是,如果不是,则更新为否。

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'

并将其嵌套在更新中,以便仅使用no或yes ...

更新相关列

1 个答案:

答案 0 :(得分: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';