2010-03-27 140 views
25

我發現了一些與在這裏更新一個現場工作:http://www.karlrixon.co.uk/articles/sql/update-multiple-rows-with-different-values-and-a-single-sql-query/使用一個查詢更新多行?

UPDATE person 
    SET name = CASE id 
     WHEN 1 THEN 'Jim' 
     WHEN 2 THEN 'Mike' 
     WHEN 3 THEN 'Precious' 
    END 
WHERE id IN (1,2,3) 

我的問題是如何更新多個字段?如:

UPDATE person 
    SET name = CASE, sex = CASE id 
     WHEN 1 THEN 'Jim', 'female' 
     WHEN 2 THEN 'Mike', 'male' 
     WHEN 3 THEN 'Precious', 'male' 
    END 
WHERE id IN (1,2,3) 

當然不行。嘗試了幾個其他組合,失敗了。任何想法?謝謝!

回答

40
UPDATE person 
    SET name = CASE id 
     WHEN 1 THEN 'Jim' 
     WHEN 2 THEN 'Mike' 
     WHEN 3 THEN 'Precious' 
    END, 
    sex = CASE id 
     WHEN 1 THEN 'female' 
     WHEN 2 THEN 'male' 
     WHEN 3 THEN 'male' 
    END 
WHERE id IN (1,2,3) 
7

你試過類似下面的東西。每列可以有多個「SET」語句。

UPDATE person 
    SET name = CASE id 
     WHEN 1 THEN 'Jim' 
     WHEN 2 THEN 'Mike' 
     WHEN 3 THEN 'Precious' 
    END, 
    sex = CASE id 
     WHEN 1 THEN 'female' 
     WHEN 2 THEN 'male' 
     WHEN 3 THEN 'male' 
    END 
WHERE id IN (1,2,3)