Skip to content
Advertisement

UPDATE with INNER JOIN on SQL Server

I have 2 tables Users and Orders. Primary key of Users is UserId, which I have defined as foreign key in the Orders table. I have added a new column of UserName to Orders. I want to import UserName from Users table.

I’m trying to run this code, but it keeps giving me errors. Can someone tell me what could be wrong?

UPDATE Orders 
SET Orders.UserName = Users.UserName 
INNER JOIN Users ON Orders.UserId = Users.UserId;

Advertisement

Answer

That’s not the right syntax

UPDATE O 
SET O.UserName = U.UserName 
from Orders O
INNER JOIN Users U ON O.UserId = U.UserId ;

You need to start using Alias for tables references when there is more than one table involved in your query. Using Alias names makes the query more readable.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement