FIX: SQL Server 2014, 2016 and 2017 do not perform the requested pre-row assignments when you use MERGE statement that performs assignments of local variables for each row

Applies to: SQL Server 2016 Service Pack 2SQL Server 2016 DeveloperSQL Server 2016 Enterprise

Symptoms


Assume that you use MERGE statement to find out how many rows are not matched by source and store it in a local variable as follows:

DECLARE
  @NotMatchedBySource INT = 0;

MERGE TargetTable USING SourceTable ON TargetTable.id = SourceTable.id
WHEN NOT MATCHED BY SOURCE THEN
  UPDATE SET @NotMatchedBySource = @NotMatchedBySource + 1;

PRINT @NotMatchedBySource;
GO

In this situation, you may notice that the value of @NotMatchedBySource after the MERGE statement may not reflect the actual number of rows that are not matched by source.

Status


Microsoft has confirmed that this is a problem in the Microsoft products that are listed in the "Applies to" section. 

Resolution


This issue is fixed in the following cumulative updates for SQL Server

About cumulative updates for SQL Server:

Each new cumulative update for SQL Server contains all the hotfixes and all the security fixes that were included with the previous cumulative update. Check out the latest cumulative updates for SQL Server:

References


Learn about the terminology that Microsoft uses to describe software updates.