仅在值更改时更新

仅在值更改时更新

本文介绍了合并-仅在值更改时更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在SQL Server中运行合并.在我的更新中,我只想更新值已更改的行.版本行在每次更新时都会递增.下面是一个示例:

I am running a merge in SQL Server. In my update, I want to only update the row if the values have changed. There is a version row that increments on each update. Below is an example:

MERGE Employee as tgt USING
(SELECT Employee_History.Emp_ID
, Employee_History.First_Name
, Employee_History.Last_Name
FROM Employee_History)
as src (Emp_ID,First_Name,Last_Name)
ON tgt.Emp_ID = src.Emp_ID
WHEN MATCHED THEN
    UPDATE SET
    Emp_ID = src.Emp_ID,
    ,[VERSION] = tgt.VERSION + 1
    ,First_Name = src.First_Name
    ,Last_Name = src.Last_Name
WHEN NOT MATCHED BY target THEN
    INSERT (Emp_ID,0,First_Name,Last_Name)
VALUES
    (src.Emp_ID,[VERSION],src.First_Name,src.Last_Name);

现在,如果我只想更新行,从而增加版本,则仅在名称更改的情况下.

Now, if I only wanted to update the row, and thus increment version, ONLY if the name has changed.

推荐答案

WHEN MATCHED可以具有AND.另外,无需更新EMP_ID.

WHEN MATCHED can have AND . Also, no need to update EMP_ID .

...
 WHEN MATCHED AND (trg.First_Name <> src.First_Name
   OR trg.Last_Name <> src.Last_Name) THEN UPDATE
   SET
   [VERSION] = tgt.VERSION + 1
    ,First_Name = src.First_Name
    ,Last_Name = src.Last_Name
 ...

如果Last_Name或First_Name可为空,则在比较trg.Last_Name<> src.Last_Name时,例如ISNULL(trg.Last_Name,'') <> ISNULL(src.Last_Name,'')

If Last_Name or First_Name are nullable, you need to take care of NULL values while comparing trg.Last_Name <> src.Last_Name , for instance ISNULL(trg.Last_Name,'') <> ISNULL(src.Last_Name,'')

这篇关于合并-仅在值更改时更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 00:02