2012-02-28 75 views
2

我有一個臨時表,其中包含多個不同的客戶記錄,如果它們具有相同的電子郵件地址,我想要更新同一列中的所有行:SQL Server - 在UPDATE語句中加入

CustomerID | Email | Pref1 | Pref2 | Pref3 
----------------------------------------------------- 
1234 [email protected] 1 0 0 
1235 [email protected] 1 1 0 
1236 [email protected] 0 0 1 
1237 [email protected] 0 0 0 
1238 [email protected] 1 0 0 

應該改爲:

CustomerID | Email | Pref1 | Pref2 | Pref3 
----------------------------------------------------- 
1234 [email protected] 1 1 1 
1235 [email protected] 1 1 1 
1236 [email protected] 1 1 1 
1237 [email protected] 1 0 0 
1238 [email protected] 1 0 0 

目前,我有一個while循環(循環比那些尚未更新的行),包含一個內部光標遍歷我想更新的列(PREF1 ,Pref2,Pref3等)。這是有效的,但是會在更大的記錄集上永久存在。

我如何修改如下:

UPDATE #table 
SET Pref1 = 
    (
    SELECT MAX(IsNull(Pref1,0)) 
    FROM #table 
    WHERE Email = '[email protected]' 
) 
WHERE Email = '[email protected]' 

,這樣,而不是傳遞每一個電子郵件地址,在某種程度上是指它的更新記錄的電子郵件地址?

UPDATE #table 
SET Pref1 = 
    (
    SELECT MAX(IsNull(Pref1,0)) 
    FROM #table 
    WHERE Email = #table.email 
) 

(上面的查詢不起作用,它只是更新了所有記錄的是整列1,如果該列存在)。我應該使用某種更新連接嗎?

回答

4

如果您使用的是SQL Server 2005或更高版本:

WITH maxvalues AS (
    SELECT 
    *, 
    MaxPref1 = MAX(Pref1) OVER (PARTITION BY Email), 
    MaxPref2 = MAX(Pref2) OVER (PARTITION BY Email), 
    MaxPref3 = MAX(Pref3) OVER (PARTITION BY Email) 
    FROM #table 
) 
UPDATE maxvalues 
SET 
    Pref1 = ISNULL(MaxPref1, 0), 
    Pref2 = ISNULL(MaxPref2, 0), 
    Pref3 = ISNULL(MaxPref3, 0) 
+0

完美,正是我一直在尋找。謝謝! – TheTor 2012-02-29 10:42:22

0

你可以做到這一點與派生表,得出每個電子郵件地址各人喜好的最大值:

update #table 
set Pref1 = mPref1, 
    Pref2 = mPref2, 
    Pref3 = mPref3 
from #table t 
    inner join (select Email, max(Pref1) mPref1, max(Pref2) mPref2, max(Pref3) mPref3 
       from #table 
       group by Email) m on m.Email = t.Email 
0

怎麼這樣呢?當然,你需要適應你的環境,但應該是一個很好的工作模板。

UPDATE 
#table1 

SET 
#table1.Pref1 = #table2.YourIsNullThingy 

FROM 
#table1 INNER JOIN #table2 
    ON #table1.Email= #table2.Email 

WHERE 
#table2.Email IN (value1,value2,...) 
0

試試這個:

UPDATE t1 
SET t1.Pref1 = ot2.newPref1 
, t1.Pref2 = ot2.newPref2 
, t1.Pref3 = ot2.newPref3 
FROM testTable AS t1 
OUTER APPLY 
(SELECT MAX(IsNull(t2.Pref1, 0)) AS newPref1 
, MAX(IsNull(t2.Pref2, 0)) AS newPref2 
, MAX(IsNull(t2.Pref3, 0)) AS newPref3 
FROM testTable t2 
where t2.e = t1.e) 
ot2