SQL Server 2008 Update Query with Join and Where clause in joined table

toddm picture toddm · Sep 20, 2010 · Viewed 55.9k times · Source

Not sure why this is not working:

UPDATE 
    ust
SET  
    ust.isUnsubscribedFromSystemEmails = 1
FROM         
    UserSetting AS ust 
INNER JOIN
    [User] ON ust.userID = [User].userID 
AND 
    [User].emailAddress IN (SELECT emailAddress FROM BadEmailAddresses)

In plain English, I am trying to set the isUnsubscribed field to unsubscribed where the userID in the UserSetting table equals the userID in the user table and where the emailAddress in the user table is not in a list of emails from another table. I can run a select on the isUnsubbed column using pretty much the same syntax and it works fine? thanks!

P.S. I've looked at other similar questions here and the syntax appears the same but obviously I'm missing something.

Answer

HLGEM picture HLGEM · Sep 20, 2010

Yep you've overlooked something.

The set statement cannot reference the alias on the left side of the set.

Try:

UPDATE  
    ust 
SET   
    isUnsubscribedFromSystemEmails = 1 
--select *
FROM          
    UserSetting AS ust  
INNER JOIN 
    [User] ON ust.userID = [User].userID  
WHERE [User].emailAddress IN (SELECT emailAddress FROM BadEmailAddresses) 

I added the commented out select so you can check to see that you aregetting results set you wanted.