Sql-Server

如果 ON 列中有 NULL,則 WHEN MATCHED 子句失敗

  • December 3, 2018

WHEN MATCHED如果 ON 子句中的所有列都有一個值,但如果其中一列中有 NULL 標記,則我正在使用帶有合併的查詢,該查詢工作正常:

MERGE PEPS AS peps
USING (Lots of Cols..
      FROM PEPS_temp) 
AS temp (Lots of Cols..) 
ON peps.[Name] = temp.[Name] AND 
  peps.[LastName] = temp.[LastName] AND 
  peps.[TypeEntity] = temp.[TypeEntity] AND
  peps.[Source] = temp.[Source]
WHEN MATCHED THEN
UPDATE SET peps.[Category] = temp.[Category] 
WHEN NOT MATCHED THEN
INSERT (Lots of Cols..) VALUES (temp.[Col], temp.[Col], temp[Col]....)

案例:我有目標表,我首先手動更新它的類別列,所以我將Category='EX BLOCKED'源表設置為更新的列表,所以如果它存在於源表中,子句WHEN MATCHED應該更新Category'BLOCKED',如果不WHEN NOT MATCHED插入新行不存在。

查詢成功執行,並且在檢查列表時我檢測到重複項:

;WITH Duplicados
    AS (Select ROW_NUMBER() OVER  (PARTITION BY Name, LastName, TypeEntity, Source ORDER BY ( SELECT 0)) RowNum, Name, LastName, TypeEntity, Source
        FROM [PEPS])
SELECT * FROM Duplicados
WHERE  RowNum > 1 AND Source='OFAC SDN';

ON所有重複行在子句的至少一列中都包含 NULL 標記。

例子:

在此處輸入圖像描述

MATCH 的謂詞不會失敗,它的行為與預期的完全一樣。NULL 不是值,NULL 是表示沒有值的狀態。因此,任何與 NULL 進行任何比較的謂詞都將解析為“UNKNOWN”而不是“TRUE”,從而導致該行被視為不匹配。為了解決這個問題,您需要確定邏輯以及在有 NULL 的情況下如何評估行。例如,如果 It is only for last name,並且您想將其視為匹配項,則可以通過擴展謂詞來處理 NULL 來解決它:

MERGE PEPS AS peps
USING (Lots of Cols..
      FROM PEPS_temp) 
AS temp (Lots of Cols..) 
ON peps.[Name] = temp.[Name] AND 
  (peps.[LastName] = temp.[LastName] OR peps.LastName IS NULL) AND 
  peps.[TypeEntity] = temp.[TypeEntity] AND
  peps.[Source] = temp.[Source]
WHEN MATCHED THEN
UPDATE SET peps.[Category] = temp.[Category] 
WHEN NOT MATCHED THEN
INSERT (Lots of Cols..) VALUES (temp.[Col], temp.[Col], temp[Col]....)

引用自:https://dba.stackexchange.com/questions/224027