Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 953
toddm Avatar asked Sep 20 '10 15:09

toddm


2 Answers

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.

like image 83
HLGEM Avatar answered Sep 25 '22 14:09

HLGEM


Although the UPDATE...FROM syntax is essential in some circumstances, I prefer to use subqueries whenever possible. Does this do what you need?

UPDATE UserSetting
SET isUnsubscribedFromSystemEmails = 1
WHERE userID in (SELECT userID from [User]
                WHERE emailAddress in (SELECT emailAddress FROM BadEmailAddresses))
like image 20
Paul Spangle Avatar answered Sep 23 '22 14:09

Paul Spangle