插入INTO NOT EXISTS SQL访问

时间:2015-02-02 16:23:16

标签: sql vba ms-access insert access-vba

我正在尝试使用sql将另一个表中的记录插入Access中的表中。我已粘贴以下声明。我想插入ImportMetricsIDs01262015中存在但不存在于ShouldImportMetricsIDs中的记录。它运行完美,没有任何错误,但即使我在实际添加新记录时也不会插入任何内容。

INSERT INTO ShouldImportMetricsIDsTable ( [Formulary ID], [Market Segment] )
SELECT ImportMetricsIDs01262015.[Formulary ID], ImportMetricsIDs01262015.[Market Segment]
FROM ImportMetricsIDs01262015
WHERE NOT EXISTS (SELECT *
FROM ShouldImportMetricsIDsTable);

3 个答案:

答案 0 :(得分:3)

您需要一个关联条款。子查询只检查表是否为空。类似的东西:

INSERT INTO ShouldImportMetricsIDsTable( [Formulary ID], [Market Segment] )
    SELECT im.[Formulary ID], im.[Market Segment]
    FROM ImportMetricsIDs01262015 as im
    WHERE NOT EXISTS (SELECT 1
                      FROM ShouldImportMetricsIDsTable as sim
                      WHERE im.[Formulary ID] = sim.[Formulary ID] AND
                            im.[Market Segment] = sim.[Market Segment]
                     );

答案 1 :(得分:0)

您需要将NOT Exist查询与ImportMetricsIDs01262015

相关联

此代码假设FormularyID是两个表中的键。

INSERT INTO ShouldImportMetricsIDsTable (
    [Formulary ID]
    ,[Market Segment]
    )
SELECT ImportMetricsIDs01262015.[Formulary ID]
    ,ImportMetricsIDs01262015.[Market Segment]
FROM ImportMetricsIDs01262015
WHERE NOT EXISTS (
        SELECT *
        FROM ShouldImportMetricsIDsTable
        where ShouldImportMetricsIDsTable.[Formulary ID] = ImportMetricsIDs01262015.[Formulary ID]
        );

答案 2 :(得分:0)

关键字" TOP"在访问中是必要的,在代码中使用粗体和斜体

INSERT INTO ShouldImportMetricsIDsTable( [Formulary ID], [Market Segment] )
SELECT im.[Formulary ID], im.[Market Segment]
FROM ImportMetricsIDs01262015 as im
WHERE NOT EXISTS (SELECT 
***TOP*** 1
                  FROM ShouldImportMetricsIDsTable as sim
                  WHERE im.[Formulary ID] = sim.[Formulary ID] AND
                        im.[Market Segment] = sim.[Market Segment]
                 );