2013-10-03 116 views
1

我正在做一個SQL Server臨時表的簡單更新。當我用三個單獨的語句更新單個列時,我得到的結果不一致,但是當我在單個SQL語句內更新同一列時,我獲得了預期的期望值。請有人指出兩者之間的區別。我錯過了什麼嗎?SQL Server更新列導致結果不一致

這裏是SQL:

CREATE TABLE #EmailChanges 
(
    OldEmail varchar(100), 
    NewEmail varchar(100) 
) 

INSERT INTO #EmailChanges(OldEmail) 
VALUES 
('[email protected]'), 
('[email protected]'), 
('[email protected]') 

UPDATE #EmailChanges SET NewEmail = replace(OldEmail, '@ccc.abc.com', '@new.domain.com') 
UPDATE #EmailChanges SET NewEmail = replace(OldEmail, '@xyz.com', '@new.domain.com') 
UPDATE #EmailChanges SET NewEmail = replace(OldEmail, '@abc.com', '@new.domain.com') 

-- If I uncomment below sql and comment above three updates, I get desired output. 
-- UPDATE #EmailChanges SET NewEmail = replace(replace(replace(OldEmail, '@ccc.abc.com', '@new.domain.com'), '@xyz.com', '@new.domain.com'), '@abc.com', '@new.domain.com') 

SELECT * FROM #EmailChanges 

這GIVENS我下面的結果:

OldEmail    NewEmail 
--------------------- -------------------------- 
[email protected] [email protected] 
[email protected] [email protected] 
[email protected]  [email protected] 

任何想法?

回答

3

根據OldEmail中的值,您的更新將在所有行中設置NewEmail的值。第三次更新將覆蓋前兩次更新。

所以前兩個是毫無意義的。它與剛纔運行的一樣

UPDATE #EmailChanges SET NewEmail = replace(OldEmail, '@abc.com', '@new.domain.com') 

而且只改變一行。

對於單獨的語句來工作,你可以使用

UPDATE #EmailChanges SET NewEmail = replace(OldEmail, '@ccc.abc.com', '@new.domain.com') 
UPDATE #EmailChanges SET NewEmail = replace(NewEmail, '@xyz.com', '@new.domain.com') 
UPDATE #EmailChanges SET NewEmail = replace(NewEmail, '@abc.com', '@new.domain.com') 
+0

感謝馬丁!傻我! :( –