IDで結合して、最初のテーブルを2番目の値で更新する必要があるt-sql演習を解決しようとしています。参加できない場合は、デフォルト ID の値を使用します (デフォルト ID は null の ID です)
実行して確認してください
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
ここに結果があります
--@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
最後の行の val を 11 にする方法は?
4 11