更新WHERE NOT EXISTS问题

时间:2011-08-02 08:49:10

标签: sql sql-server sql-server-2005

只要tbl1中存在多于1条记录且tbl1_temp中没有

,该查询就会出错

如何解决此问题,以便对于tbl1_temp中不存在的每条记录,更新tbl1中相应记录的状态

UPDATE tbl1 SET Status = 'Finished' 
WHERE id = (SELECT id 
FROM tbl1 
WHERE NOT EXISTS (SELECT id FROM tbl1_temp 
WHERE tbl1.id = tbl1_temp.id))

4 个答案:

答案 0 :(得分:11)

UPDATE tbl1
SET Status = 'Finished' 
WHERE NOT EXISTS (SELECT id FROM tbl1_temp 
    WHERE tbl1.id = tbl1_temp.id)

答案 1 :(得分:3)

直接使用NOT EXISTS

UPDATE tbl1
SET Status = 'Finished' 
WHERE NOT EXISTS (SELECT * FROM tbl1_temp
                WHERE tbl1.id = tbl1_temp.id)

答案 2 :(得分:1)

等于运算符仅适用于单个值,而不适用于多个值,因此错误。因此,使用IN

而不是等式
... WHERE id IN (SELECT ...)

答案 3 :(得分:1)

UPDATE tbl1 SET Status = 'Finished' 
WHERE id **IN** (SELECT id 
FROM tbl1 
WHERE NOT EXISTS (SELECT id FROM tbl1_temp 
WHERE tbl1.id = tbl1_temp.id))