CorribView
CorribView

Reputation: 741

SQL Server Update Query using join not working

I'm unable to update a table using the following join on another table. Basically TableA has some null values in its Name column and I'm trying to add them from the Customer tables Name column, joining on the ID column.

UPDATE
    TableA
SET
    TableA.Name = Customer.Name
FROM
    TableA
INNER JOIN
    Customer ON Customer.ID = TableA.ID
WHERE
    TableA.Name <> Customer.Name

I've also tried it where the last line is:

TableA.Name = null 

Upvotes: 0

Views: 3220

Answers (2)

Tab Alleman
Tab Alleman

Reputation: 31785

Why have a WHERE clause at all? If you want the names to be equal based on the ID, just do this:

UPDATE
    TableA
SET
    TableA.Name = Customer.Name
FROM
    TableA
INNER JOIN
    Customer ON Customer.ID = TableA.ID

Or if you must have a WHERE clause for performance, it should be this:

WHERE TableA.Name IS NULL OR TableA.Name <> Customer.Name

Upvotes: 0

Clay Sills
Clay Sills

Reputation: 235

UPDATE
    TableA
SET
    TableA.Name = Customer.Name
FROM
    TableA
INNER JOIN
    Customer ON Customer.ID = TableA.ID
WHERE
    TableA.Name is null

you can't do logical evaluation of null, so you gotta use is or is not, depending on your needs.

Upvotes: 2

Related Questions