Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

SQL Server – Update Table with INNER JOIN

Often we may need to update a column in a table based of another column in another table.

In SQL Server you can do this using UPDATE statement by joining tables together.

To understand this better let’s take a look at below contrived example.

USE [SqlAndMe]

GO

 

SELECT CustomerID, Name, OrderAmount

FROM   dbo.Customers

GO

 

SELECT OrderID, CustomerID, Amount

FROM   dbo.Orders

GO

Result Set:

CustomerID    Name          OrderAmount

3             Curtis        NULL

4             Lanna         NULL

5             Marlin        NULL

6             Henry         NULL

 

(4 row(s) affected)

 

OrderID       CustomerID    Amount

107           6             8745.00

123           5             4582.00

643           3             5693.00

 

(3 row(s) affected)

In the above data I want to update OrderAmount column of dbo.Customers with values from Amount column of dbo.Orders.

To achieve this we can use UPDATE statement as below:

UPDATE CUST

SET    CUST.OrderAmount = ORDR.Amount

FROM   dbo.Customers CUST

INNER JOIN dbo.Orders ORDR ON CUST.CustomerID = ORDR.CustomerID

GO

 

(3 row(s) affected)

OrderAmount column in dbo.Customers Table is now updated based on JOIN condition.

SELECT CustomerID, Name, OrderAmount

FROM   dbo.Customers

GO

CustomerID    Name          OrderAmount

3             Curtis        5693.00

4             Lanna         NULL

5             Marlin        4582.00

6             Henry         8745.00

 

(4 row(s) affected)

 

I have used a simple example here to explain the concept easily

Hope This Helps!

Vishal

If you like this post, do like my Facebook Page -> SqlAndMe
EMail me your questions -> Vishal@SqlAndMe.com
Follow me on Twitter -> @SqlAndMe


Filed under: SQLServer, SQLServer 2005, SQLServer 2008, SQLServer 2008 R2, SQLServer 2012, Working With Data

Comments

Leave a comment on the original post [sqlandme.com, opens in a new window]

Loading comments...