2013-07-29 32 views
2

我有表有兩個FK UserProfile_IdService_Id。該表包含我需要更改的值字段。選取元組在聲明中

我有兩個臨時表:

第一臺#TEMP2

EmailAddress, 
UserProfile_Id 

二表#TEMP

EmailAddress, 
Service_Id 

此語句不起作用:

UPDATE MailSubscription SET BitField=1 
where UserProfile_id IN (SELECT UserProfile_Id from #temp2) 
     and Service_id IN (SELECT ServiceId from #temp) 

我知道爲什麼它不工作,但不知道如何解決它做工精細。

我需要改變bitFieldMailSubscription其中元組(UserProfile_Id,SERVICE_ID)在加入#TEMP和#TEMP2,但我不能在MSSQL是這樣寫。

+0

爲什麼它不工作?你有錯誤還是不更新預期的行? – Parado

+0

@Parado它不會更新有效的行,因爲我需要一次搜索2列而不是單獨搜索 – wudzik

回答

3
UPDATE M 
SET M.BitField=1 
from MailSubscription M 
inner join #temp2 t2 on M.UserProfile_id=t2.UserProfile_Id 
inner join #temp t on M.Service_id=t.ServiceId 
and t.EmailAddress=t2.EmailAddress 
+0

非常感謝,完美的答案:) – wudzik

2
UPDATE MailSubscription SET BitField=1 
FROM #temp2 
JOIN #temp on #temp2.EmailAddress=#temp.EmailAddress 
WHERE MailSubscription.Service_id = #temp.ServiceId 
    AND MailSubscription.UserProfile_id = #temp2.UserProfile_Id 
+0

+1不知道你可以省略'from'子句中的更新表,並且仍然參考它,但它實際上工作 – Andomar

2

你可以使用過濾聯接:

update m 
set  BitField = 1 
from MailSubscription m 
join #temp t1 
on  t1.Service_id = m.Service_id 
join #temp2 t2 
on  t2.UserProfile_Id= m.UserProfile_Id 
     and t1.EmailAddress = t2.EmailAddress 
+0

@Parado:你說得對,'#temp2'應該已經被連接到'UserProfile_id',在答案中更新。 – Andomar

0

與另一種選擇EXISTS操作

UPDATE MailSubscription 
SET BitField = 1 
WHERE EXISTS (
       SELECT 1 
       FROM #temp2 t2 JOIN #temp t ON t2.EmailAddress = t.EmailAddress 
       WHERE t2.UserProfile_Id = MailSubscription.UserProfile_Id 
       AND t.Service_Id = MailSubscription.Service_Id 
      ) 
0

我想這應該幫助ü找到答案。

Update 'Tablename' 
SET Mailsubscription = 1 
WHERE concat(UserProfile_Id ,".", Service_Id) IN ( 
         SELECT concat(t.UserProfile_Id , "." , t2,Service_Id) 
         FROM #temp t INNER JOIN #temp2 t2 
           ON t2.EmailAddress = t.EmailAddress) 
0
update MailSubscription set 
    BitField = 1 
from MailSubscription as MS 
where 
    exists 
    (
     select * 
     from #temp2 as T2 
      inner join #temp as T on T.EmailAddress = T2.EmailAddress 
     where 
      T2.UserProfile_Id = MS.UserProfile_Id and 
      T.Service_Id = MS.Service_Id 
    )