This question already has answers here:
T-SQL CASE Clause: How to specify WHEN NULL (18 answers)
Closed 24 days ago.
Let's say I have 2 tables (Table1 and Table2) with same structure
- int Id
- string Name
Ex:
Table1: (1,'abc'), (2,'xxx'), (3, 'mm')
Table2: (1,'abcd'), (3, 'nnnn')
The goal is to display data from Table1 if there is no data for the same Id in Table2 or from Table2 when there is such data
For the tables above, the data returned will be:
(1, 'abcd') -- from Table2
(2, 'xxx') -- from Table1
(3, 'nnnn') -- from Table2
This is what I tried:
select Table1.Id,
case Table2.Name
when null then Table1.Name
else Table2.Name
end as Name
from Table1
left join Table2 on Table2.Id = Table1.Id
but doesn't work
1条答案
按热度按时间enxuqcxy1#
Your CASE WHEN is somewhat wrong, you need IS to check for NULL
3 rows affected
2 rows affected
fiddle