【发布时间】:2020-10-08 09:43:36
【问题描述】:
drop table #source
create table #source
(
userid int NULL,
col1 nvarchar(max) NULL,
col2 nvarchar(max) NULL,
col3 nvarchar(max) NULL,
)
drop table #target
create table #target
(
userid int NULL,
col1 nvarchar(max) NULL,
col2 nvarchar(max) NULL,
col3 nvarchar(max) NULL,
col4 nvarchar(max) NULL,
)
insert into #source values(1,'A','','B')
insert into #source values(2,'a',NULL,'b')
insert into #target values(1,NULL,'B','','extra')
insert into #target values(2,'aa',NULL,'b','extra')
select * from #source
select * from #target
update #target
set col1 = s.col1,
col2 = s.col2,
col3 = s.col3
from #target t
inner join #source s
on s.userid = t.userid
where
s.col1 <> t.col1 or s.col1 is null and t.col1 is not null or s.col1 is not null and t.col1 is null
OR s.col2 <> t.col2 or s.col2 is null and t.col2 is not null or s.col2 is not null and t.col2 is null
OR s.col3 <> t.col3 or s.col3 is null and t.col3 is not null or s.col3 is not null and t.col3 is null
update #target
set
col1 = CASE WHEN s.col1 <> t.col1 or s.col1 is null and t.col1 is not null or s.col1 is not null and t.col1 is null THEN s.col1 ELSE t.col1 END,
col2 = CASE WHEN s.col2 <> t.col2 or s.col2 is null and t.col2 is not null or s.col2 is not null and t.col2 is null THEN s.col2 ELSE t.col2 END,
col3 = CASE WHEN s.col3 <> t.col3 or s.col3 is null and t.col3 is not null or s.col3 is not null and t.col3 is null THEN s.col3 ELSE t.col3 END
from #target t
inner join #source s
on s.userid = t.userid
我只想在给定列的值不同时更新,并且还要考虑性能。非常感谢任何见解。提前致谢。看了很多线程,才知道如果值相同,SQL内部不会执行更新。
【问题讨论】:
-
如果值相同,
update仍会导致更新;尚未在最新版本中对其进行测试,但我非常确信更新不关心值是否更改,无论如何它都会将新版本写入磁盘。无论如何,找出最有效的方法的最简单方法就是尝试一下。
标签: sql-server sql-update query-optimization