我想使用CASE语句更新sql server 2005中的某些记录


179
UPDATE dbo.TestStudents  
SET LASTNAME = 
( CASE  
WHEN (LASTNAME = 'AAA') THEN 'BBB' 
WHEN (LASTNAME = 'CCC') THEN 'DDD' 
WHEN (LASTNAME = 'EEE') THEN 'FFF' 
ELSE  (LASTNAME)
END )

该语句出于该目的而工作,但else条件遍历表中的每个记录。有什么办法可以让未受影响的行保持原样?

Answers:


336

添加WHERE子句

UPDATE dbo.TestStudents  
SET     LASTNAME =  CASE  
                        WHEN LASTNAME = 'AAA' THEN 'BBB' 
                        WHEN LASTNAME = 'CCC' THEN 'DDD' 
                        WHEN LASTNAME = 'EEE' THEN 'FFF' 
                        ELSE LASTNAME
                    END 
WHERE   LASTNAME IN ('AAA', 'CCC', 'EEE')
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.