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

2022-01-17 00:00:00 sql-update sql tsql sql-server
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 条件扫描表中的每条记录.有什么办法可以让未受影响的行保持原样?

The statement work for the purpose but the else condition scan through every record in the table. Is there any way I can leave the unaffected rows as they are?

推荐答案

添加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')

相关文章