Use Where Clause With Merge

Use Where Clause With Merge

 

There is no WHERE in that part of the MERGE statement. See MERGE (Transact-SQL) in the documentation for syntax help.

There is an optional AND part in WHEN MATCHED clause so the straightforward answer is to move the condition there:

MERGE @Emp emp
USING @EmpUpdates eup
ON emp.empid = eup.empid
WHEN MATCHED 
     AND emp.empaddress <> eup.empaddress
  THEN
    UPDATE
    SET emp.empaddress = eup.empaddress
WHEN NOT MATCHED BY TARGET 
  THEN 
    INSERT (empid, empaddress)
    VALUES (eup.empid, eup.empaddress) ;

Be careful to handle nulls correctly there (if empaddress is nullable).

It is sometimes more explicit (and efficient) to perform the operations in two separate statements (UPDATE and INSERT in your case) in a transaction.

Also, be aware there have been (and still are) some issues with MERGE.

 

 

 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-11-14 使用sql compare生成的sql语句
2018-11-14 string interpolation in sql server
2015-11-14 Hearthstone-Deck-Tracker汉化处理技巧
2014-11-14 Asynchronous Programming Using Delegates使用委托进行异步编程
2014-11-14 通过委托来实现异步 Delegate的BeginInvoke和EndInvoke
2014-11-14 DataSet 和 DataTable 以及 DataRow
点击右上角即可分享
微信分享提示