To get all rows from T1
when joining to table T2
that is lacking the rows 2 and 4 you need to use a left outer join. For row 2 and 4 salary will be null.
To replace the null value with something else you can use coalesce. Coalesce returns the first nonnull argument.
Since field salary
is declared as an int
field and you want No Salary
as output where there is no salary you need to cast the int
to a varchar
before using it as an argument in coalesce.
declare @T1 table(id int, name varchar(10))
declare @T2 table(id int, salary int)
insert into @T1 values(1, 'Sue')
insert into @T1 values(2, 'Sarah')
insert into @T1 values(3, 'Nick')
insert into @T1 values(4, 'james')
insert into @T2 values(1, 10000)
insert into @T2 values(3, 9000)
select
T1.id,
T1.name,
coalesce(cast(T2.salary as varchar(10)), 'No Salary') as salary
from @T1 as T1
left outer join @T2 as T2
on T1.id = T2.id
Result
id name salary
----------- ---------- ----------
1 Sue 10000
2 Sarah No Salary
3 Nick 9000
4 james No Salary