如何解决根据条件更新多个列,哪种方法性能更好或者是否有其他更好的方法
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,col4 nvarchar(max) NULL,)
insert into #source values(1,'A','','B')
insert into #source values(2,'a',NULL,'b')
insert into #target values(1,'B','extra')
insert into #target values(2,'aa','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内部不会执行更新。
解决方法
- 确保两个表都在user_id上建立索引(群集)。
- 仅出于可读性考虑,在所有
AND
和OR
中添加一些括号。
您的第一个update
将执行您期望的操作:仅更新有差异的记录。第二个update
将更新ALL(与用户ID匹配)记录。
在性能方面,第一个记录对于系统而言可能会容易得多,因为实际记录数可能大大低于记录总数。
在极端情况下,您可能会争辩说 IF 所有记录都需要更新,那么第二个版本中更简单的INNER JOIN
在系统上可能会稍微容易一些,但是在这种情况下,您可以摆脱CASE..WHEN..THEN
的构造,因为坦率地说,它实际上并没有添加任何内容:将字段设置为某个值时,该值与以前是否相同根本无关紧要。>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。