将值A更改为B,无论它在哪个列中

时间:2015-07-09 12:41:55

标签: sql sql-server

单一更新工作:

UPDATE users SET email=@newemail WHERE email=@oldemail
(1 Zeile(n) betroffen)

Double UPDATE无效:

UPDATE users SET email=@newemail WHERE email=@oldemail, alternateEmail=@newemail WHERE alternateEmail=@oldEmail
Meldung 102, Ebene 15, Status 1, Zeile 1
Incorrect syntax near ','.

如何在单个语句中执行此操作(即使我要检查N列)?

澄清:如果我有桌子

email     alternateEmail
a@b.c     d@e.f
d@e.f     a@b.c

我设置了@oldemail='a@b.c'@newemail='g@h.i',结果表应为

email     alternateEmail
g@h.i     d@e.f
d@e.f     g@h.i

我知道我可以在2(或N)个陈述中做到这一点:

UPDATE users SET email=@newemail WHERE email=@oldemail
UPDATE users SET alternateEmail=@newemail WHERE alternateEmail=@oldEmail

但是我可以在一个声明中这样做吗?

1 个答案:

答案 0 :(得分:4)

你可以这样做:

UPDATE users SET 
    email = case 
               when email = @oldemail then @newemail 
               else email 
            end,
    alternateEmail = case 
                       when alternateEmail = @oldemail then @newemail 
                       else alternateEmail 
                     end
where 
    email = @oldemail 
    or alternateEmail = @oldemail