ACCADemy ACCADemy
ACCADemy ACCADemy

Reputation: 23

SQL Server case statement with null

I have two tables Source and Destination. I need to update Name column in Destination table with that of Source table if Destination name column is null or blank. But somehow Case statement doesn't work properly

Update d
Set name = Case when nullif(d.name,'') is null then s.name else null end
From destination d join
Source s on d.id = s.id
Where nullif(d.name,'') is null

Upvotes: 0

Views: 220

Answers (2)

Serkan Arslan
Serkan Arslan

Reputation: 13393

your null or empty filter should be like d.name = '' or d.name is null. And you don't need to use also case function. You already have a filter for null values.

Update d
Set name = s.name
From destination d join
Source s on d.id = s.id
Where d.name = '' or d.name is null

Upvotes: 1

ravioli
ravioli

Reputation: 3823

How about this?

UPDATE destination d
SET d.name = COALESCE(NULLIF(d.name,''), s.name)
FROM source s 
WHERE d.id = s.id

Assuming id is your PK, this will update rows in d with data from source with matching id values.

Upvotes: 0

Related Questions