SQL 服务器:多个 WHERE NOT EXISTS 子句

SQL Server : multiple WHERE NOT EXISTS clauses

我在 Load_Charges_IMPORT 查询中有大约 2600 行未插入到 Load_Charges 查询中。

我试图确保没有添加重复的主键条目。主键在 Load_Charges 查询中建立为复合键(费用说明 + 费用金额)。 Load_Charges_IMPORT 查询中未设置键,此数据是从 excel 文档导入的。

你能告诉我我的代码是否有问题吗?当我知道 Load_Charges_IMPORT.

中有 2600 多行时,为什么我会收到 0 row(s) affected 的响应
INSERT INTO Load_Charges
    SELECT *
    FROM Load_Charges_IMPORT
    WHERE 
        NOT EXISTS (SELECT [Load ID]
                    FROM Load_Charges
                    WHERE Load_Charges_IMPORT.[Load ID] = Load_Charges.[Load ID])
        AND NOT EXISTS (SELECT [Charge Description]
                        FROM Load_Charges
                        WHERE Load_Charges_IMPORT.[Charge Description] = Load_Charges.[Charge Description])
        AND NOT EXISTS (SELECT [Charged Amount] 
                        FROM Load_Charges
                        WHERE Load_Charges_IMPORT.[Charged Amount] = Load_Charges.[Charged Amount]);

您的 EXISTS 子句排除了任何一个条件为 TRUE 的所有行,而不仅仅是所有条件都为 TRUE 的行。试试这个:

INSERT INTO Load_Charges

SELECT *

FROM Load_Charges_IMPORT

WHERE NOT EXISTS (
    SELECT * 
    FROM Load_Charges 
    WHERE Load_Charges_IMPORT.[Load ID]=Load_Charges.[Load ID]
    AND Load_Charges_IMPORT.[Charge Description]=Load_Charges.[Charge Description]
    AND Load_Charges_IMPORT.[Charged Amount]=Load_Charges.[Charged Amount]);

解决该问题的另一种方法是使用一系列 LEFT JOIN,其中包含排除任何匹配记录的 WHERE 子句。

这是一个较短的语法,避免使用子查询。

INSERT INTO Load_Charges
SELECT imp.*
FROM 
    Load_Charges_IMPORT imp
    LEFT JOIN Load_Charges load1 ON load1.[Load ID] = imp.[Load ID]
    LEFT JOIN Load_Charges load2 ON load2.[Charge Description] = imp.[Charge Description]
    LEFT JOIN Load_Charges load3 ON load3.[Charged Amount]= imp.[Charged Amount]
WHERE load1.[Load ID] IS NULL AND load2.[Load ID] IS NULL AND load3.[Load ID] IS NULL
;

注意:这假设 [Load ID] 是 Load_Charges table 中的不可空字段。如果不是,则可以在 WHERE 子句中使用任何其他不可为 null 的字段。