I am trying to resolve t-sql exercise
I need to update first table with values from second by joining by id. If I can not join then use value from default ID (default iD is the Id that is null)
please run it to see it
declare @t as table (
[id] INT
,val int
)
insert into @t values (null, null)
insert into @t values (2, null)
insert into @t values (3, null)
insert into @t values (4, null)
declare @t2 as table (
[id] INT
,val int
)
insert into @t2 values (null, 11)
insert into @t2 values (2, 22)
insert into @t2 values (3, 33)
select * from @t
select * from @t2
update t
set t.val = t2.val
from @t as t join @t2 as t2
on t.id = t2.id
or
(
(t.id is null or t.id not in (select id from @t2))
and t2.id is null
)
select * from @t
here is result
--@t
id val
---------------
NULL NULL
2 NULL
3 NULL
4 NULL
--@t2
id val
---------------
NULL 11
2 22
3 33
--@t after update
id val
---------------
NULL 11
2 22
3 33
4 NULL
how to make val in last row equal 11?
4 11
try this for the update…
Problem is with
not inoperator andnullvalues. This would also work…