简体   繁体   中英

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!

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

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.

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))

Note: Just for the record (assuming you get everything else to work), you could also do an inner join on the BadEmailAddresses table.

If you have any performance problems, then you might want to index the emailAddress column in both tables.

Try this :

UPDATE UserSetting ust SET usr.isUnsubscribedFromSystemEmails = 1
WHERE ust.emailAdress IN (select emailAddress from bademailAddresses);

Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM